JAVA实现FFT算法
关于快速傅里叶变换(FFT)和傅里叶变换的理论知识这里我就不提了,本文主要讲解FFT实现:
之前想找一个FFT代码,在网上找了很多都是有问题的,下面我完善了一个供大家学习交流;
首先粘贴FFT的代码如下:
/******************************************************************************
-
Compilation: javac FFT.java
-
Execution: java FFT n
-
Dependencies: Complex.java
-
Compute the FFT and inverse FFT of a length n complex sequence
-
using the radix 2 Cooley-Tukey algorithm.
-
Bare bones implementation that runs in O(n log n) time. Our goal
-
is to optimize the clarity of the code, rather than performance.
-
Limitations
-
-
- assumes n is a power of 2
-
- not the most memory efficient algorithm (because it uses
-
an object type for representing complex numbers and because
-
it re-allocates memory for the subarray, instead of doing
-
in-place or reusing a single temporary array)
-
For an in-place radix 2 Cooley-Tukey FFT, see
-
https://introcs.cs.princeton.edu/java/97data/InplaceFFT.java.html
******************************************************************************/
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;
public class FFT {
// compute the FFT of x[], assuming its length is a power of 2
public static Complex[] fft(Complex[] x) {
int n = x.length;
// base case
if (n == 1) return new Complex[] { x[0] };
// radix 2 Cooley-Tukey FFT
if (n % 2 != 0) {
throw new IllegalArgumentException("n is not a power of 2");
}
// fft of even terms
Complex[] even = new Complex[n/2];
for (int k = 0; k < n/2; k++) {
even[k] = x[2*k];
}
Complex[] q = fft(even);
// fft of odd terms
Complex[] odd = even; // reuse the array
for (int k = 0; k < n/2; k++) {
odd[k] = x[2*k + 1];
}
Complex[] r = fft(odd);
// combine
Complex[] y = new Complex[n];
for (int k = 0; k < n/2; k++) {
double kth = -2 * k * Math.PI / n;
Complex wk = new Complex(Math.cos(kth),