import java.io.*;public classFFT {public static void CreateSignal(intlength, Complex[] x){double Fs = 1000; //采样频率
double T = 1 / Fs; //采样周期
System.out.println("产生幅值为 0.7 的 50 Hz正弦量和幅值为 1 的 120 Hz正弦量(一共"+length+"个)");for (int i = 0; i < length; i++) {//产生幅值为0.7的50Hz正弦量和幅值为1的120 Hz正弦量。
double S = 0.7 * Math.sin(2 * Math.PI * 50 * i * T) + Math.sin(2 * Math.PI * 120 * i *T);
x[i]= new Complex(S, 0);
}
}public staticComplex[] dft(Complex[] x) {int n =x.length;if (n == 1) //exp(-2pi*j) = cos(-2pi)+j * sin(-2pi) = 1
returnx;
Complex[] result= newComplex[n];for (int i = 0; i < n; i++) {
result[i]= newComplex();for (int k = 0; k < n; k++) {double p = -2 * k * Math.PI * i /n ;//欧拉公式e^(-j (2pi * k * i) / N) = cos(-2pi * k * i / N) + i*sin(-2pi * k * i/ N)
Complex e = newComplex(Math.cos(p), Math.sin(p));
result[i]=result[i].plus(x[k].multiply(e));
}
}returnresult;
}public staticComplex[] fft(Complex[] x) {int n =x.length;if (n == 1)returnx;//信号数为奇数不满足对称性,使用dft计算
if (n % 2 != 0)returndft(x);//取下标为偶数的信号
Complex[] even = new Complex[n / 2];for (int i = 0; i < n / 2; i++) {
even[i]= x[2 *i];
}
Complex[] evenValue=fft(even);//取下标为奇数的信号
Complex[] odd = new Complex[n / 2];for (int i = 0; i < n / 2; i++) {
odd[i]= x[2 * i + 1];
}
Complex[] oddValue=fft(odd);//相加
Complex[] result = newComplex[n];for (int i = 0; i < n / 2; i++) {double p = -2 * Math.PI * i /n ;
Complex e= newComplex(Math.cos(p), Math.sin(p));
result[i]=evenValue[i].plus(e.multiply(oddValue[i]));
result[i+ n / 2] =evenValue[i].minus(e.multiply(oddValue[i]));
}returnresult;
}public static voidwriteText(String filename,Complex[]result) {try{
File writeName= new File(filename); //相对路径,如果没有则要建立一个新文件
writeName.createNewFile(); //创建新文件,有同名的文件的话直接覆盖
try (FileWriter writer = newFileWriter(writeName);
BufferedWriter out= newBufferedWriter(writer)
) {for (int i = 0; i < result.length; i++) {
out.write(result[i].toString()+"\n"); //\r\n即为换行
}
}
}catch(IOException e) {
e.printStackTrace();
}
System.out.println("数据写入成功!");
}public static voidmain(String[] args) {int length = 1500;
Complex[] x= newComplex[length];
Complex[] result;
CreateSignal(length, x);long start1 =System.currentTimeMillis();
result=dft(x);long end1 =System.currentTimeMillis();long start2 =System.currentTimeMillis();
result=fft(x);long end2 =System.currentTimeMillis();
System.out.println("FFT结果:");for (int i = 0; i < length; i++) {
System.out.println("第"+(i+1)+"个数据:"+result[i].toString());
}
System.out.println("------------------------------------------------");
System.out.println("DFT运行时间: " + (end1 - start1) + "ms");
System.out.println("FFT运行时间: " + (end2 - start2) + "ms");
String filename= "C:\\Users\\xxx\\Desktop\\算法课程\\xxx\\shuju.txt";
writeText(filename, result);
}
}