Skip to content

Commit eb9081e

Browse files
authored
Merge pull request thuva4#383 from syam3526/patch-4
fast fourier transform using java
2 parents 3881ea2 + 637229f commit eb9081e

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import static java.lang.Math.*;
2+
3+
public class FastFourierTransform {
4+
5+
public static int bitReverse(int n, int bits) {
6+
int reversedN = n;
7+
int count = bits - 1;
8+
9+
n >>= 1;
10+
while (n > 0) {
11+
reversedN = (reversedN << 1) | (n & 1);
12+
count--;
13+
n >>= 1;
14+
}
15+
16+
return ((reversedN << count) & ((1 << bits) - 1));
17+
}
18+
19+
static void fft(Complex[] buffer) {
20+
21+
int bits = (int) (log(buffer.length) / log(2));
22+
for (int j = 1; j < buffer.length / 2; j++) {
23+
24+
int swapPos = bitReverse(j, bits);
25+
Complex temp = buffer[j];
26+
buffer[j] = buffer[swapPos];
27+
buffer[swapPos] = temp;
28+
}
29+
30+
for (int N = 2; N <= buffer.length; N <<= 1) {
31+
for (int i = 0; i < buffer.length; i += N) {
32+
for (int k = 0; k < N / 2; k++) {
33+
34+
int evenIndex = i + k;
35+
int oddIndex = i + k + (N / 2);
36+
Complex even = buffer[evenIndex];
37+
Complex odd = buffer[oddIndex];
38+
39+
double term = (-2 * PI * k) / (double) N;
40+
Complex exp = (new Complex(cos(term), sin(term)).mult(odd));
41+
42+
buffer[evenIndex] = even.add(exp);
43+
buffer[oddIndex] = even.sub(exp);
44+
}
45+
}
46+
}
47+
}
48+
49+
public static void main(String[] args) {
50+
double[] input = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0};
51+
52+
Complex[] cinput = new Complex[input.length];
53+
for (int i = 0; i < input.length; i++)
54+
cinput[i] = new Complex(input[i], 0.0);
55+
56+
fft(cinput);
57+
58+
System.out.println("Results:");
59+
for (Complex c : cinput) {
60+
System.out.println(c);
61+
}
62+
}
63+
}
64+
65+
class Complex {
66+
public final double re;
67+
public final double im;
68+
69+
public Complex() {
70+
this(0, 0);
71+
}
72+
73+
public Complex(double r, double i) {
74+
re = r;
75+
im = i;
76+
}
77+
78+
public Complex add(Complex b) {
79+
return new Complex(this.re + b.re, this.im + b.im);
80+
}
81+
82+
public Complex sub(Complex b) {
83+
return new Complex(this.re - b.re, this.im - b.im);
84+
}
85+
86+
public Complex mult(Complex b) {
87+
return new Complex(this.re * b.re - this.im * b.im,
88+
this.re * b.im + this.im * b.re);
89+
}
90+
91+
@Override
92+
public String toString() {
93+
return String.format("(%f,%f)", re, im);
94+
}
95+
}

0 commit comments

Comments
 (0)