Skip to content

Commit 6a82e2b

Browse files
committed
Adding DFT to fft.c
1 parent d9d8405 commit 6a82e2b

File tree

1 file changed

+34
-18
lines changed

1 file changed

+34
-18
lines changed

chapters/FFT/code/c/fft.c

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,27 @@
11
#include <complex.h>
22
#include <math.h>
3+
#include <stdio.h>
34
#include <stdlib.h>
45
#include <time.h>
5-
#include <stdio.h>
66

77
#define PI 3.1415926535897932384626
88

9+
void dft(double complex *X, const size_t N) {
10+
double complex tmp[N];
11+
for (size_t i = 0; i < N; ++i) {
12+
double complex sum = 0 + 0 * I;
13+
for (size_t j = 0; j < N; ++j) {
14+
sum += X[j] * cexp(-2.0 * PI * I * j * i / N);
15+
}
16+
17+
tmp[i] = sum;
18+
}
19+
20+
for (size_t i = 0; i < N; ++i) {
21+
X[i] = tmp[i];
22+
}
23+
}
24+
925
void cooley_tukey(double complex *X, const size_t N) {
1026
if (N >= 2) {
1127
double complex tmp [N / 2];
@@ -28,23 +44,22 @@ void cooley_tukey(double complex *X, const size_t N) {
2844
}
2945

3046
void bit_reverse(double complex *X, size_t N) {
31-
double complex temp;
32-
unsigned int b;
33-
34-
for (unsigned int i = 0; i < N; ++i) {
35-
b = i;
36-
b = (((b & 0xaaaaaaaa) >> 1) | ((b & 0x55555555) << 1));
37-
b = (((b & 0xcccccccc) >> 2) | ((b & 0x33333333) << 2));
38-
b = (((b & 0xf0f0f0f0) >> 4) | ((b & 0x0f0f0f0f) << 4));
39-
b = (((b & 0xff00ff00) >> 8) | ((b & 0x00ff00ff) << 8));
40-
b = ((b >> 16) | (b << 16)) >>
41-
(32 - (unsigned int) log2((double)N));
42-
if (b > i) {
43-
temp = X[b];
44-
X[b] = X[i];
45-
X[i] = temp;
46-
}
47+
double complex temp;
48+
unsigned int b;
49+
50+
for (unsigned int i = 0; i < N; ++i) {
51+
b = i;
52+
b = (((b & 0xaaaaaaaa) >> 1) | ((b & 0x55555555) << 1));
53+
b = (((b & 0xcccccccc) >> 2) | ((b & 0x33333333) << 2));
54+
b = (((b & 0xf0f0f0f0) >> 4) | ((b & 0x0f0f0f0f) << 4));
55+
b = (((b & 0xff00ff00) >> 8) | ((b & 0x00ff00ff) << 8));
56+
b = ((b >> 16) | (b << 16)) >> (32 - (unsigned int) log2((double)N));
57+
if (b > i) {
58+
temp = X[b];
59+
X[b] = X[i];
60+
X[i] = temp;
4761
}
62+
}
4863
}
4964

5065
void iterative_cooley_tukey(double complex *X, size_t N) {
@@ -80,7 +95,8 @@ int main() {
8095
}
8196

8297
cooley_tukey(y, 64);
83-
iterative_cooley_tukey(z, 64);
98+
//iterative_cooley_tukey(z, 64);
99+
dft(z, 64);
84100

85101
approx(y, z, 64);
86102

0 commit comments

Comments
 (0)