-
Notifications
You must be signed in to change notification settings - Fork 10
/
ift-dif.c
97 lines (72 loc) · 1.73 KB
/
ift-dif.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include "ift.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
static int ctz(size_t N)
{
int ctz1 = 0;
while (N) {
ctz1++;
N >>= 1;
}
return ctz1 - 1;
}
static void nop_split(const float complex *x, float complex *X, size_t N)
{
for (size_t n = 0; n < N/2; n++) {
X[2*n + 0] = x[0/2 + n];
X[2*n + 1] = x[N/2 + n];
}
}
static void fft_split(const float complex *x, float complex *X, size_t N, float complex phi)
{
for (size_t n = 0; n < N/2; n++) {
X[2*n + 0] = (x[0/2 + n] + x[N/2 + n])/2;
X[2*n + 1] = (x[0/2 + n] - x[N/2 + n])/2 * cexpf(+2*(float)M_PI*I*phi);
}
}
static size_t revbits(size_t v, int J)
{
size_t r = 0;
for (int j = 0; j < J; j++) {
r |= ((v >> j) & 1) << (J - 1 - j);
}
return r;
}
static int nop_reverse(int b, float complex *buffers[2], size_t N)
{
int J = ctz(N);
for (int j = J - 2; j >= 0; j--, b++) {
size_t delta = N >> j;
for (size_t n = 0; n < N; n += delta) {
nop_split(buffers[b&1] + n, buffers[~b&1] + n, delta);
}
}
return b;
}
static int fft_reverse(int b, float complex *buffers[2], size_t N)
{
int J = ctz(N);
for (int j = J - 1; j >= 0; j--, b++) {
size_t delta = N >> j;
for (size_t n = 0; n < N; n += delta) {
float complex phi = (float)revbits(n/delta, j) / (float)(2 << j);
fft_split(buffers[b&1] + n, buffers[~b&1] + n, delta, phi);
}
}
return b;
}
int ift(float complex *vector, size_t N)
{
if (!N) return 0;
if (N & (N - 1)) return 1;
float complex *buffers[2] = { vector, malloc(N*sizeof(float complex)) };
if (!buffers[1]) return -1;
int b = 0;
b = nop_reverse(b, buffers, N);
b = fft_reverse(b, buffers, N);
b = nop_reverse(b, buffers, N);
memmove(vector, buffers[b&1], N*sizeof(float complex));
free(buffers[1]);
return 0;
}