#include <stdio.h> #include <math.h> #define pi 3.1415926 typedef struct { float re;// really float im;// imaginary }complex, * pcomplex; complex complexadd(complex a, complex b) //复数加 { complex rt; rt.re = a.re + b.re; rt.im = a.im + b.im; return rt; } complex complexMult(complex a, complex b) //复数乘 { complex rt; rt.re = a.re * b.re - a.im * b.im; rt.im = a.im * b.re + a.re * b.im; return rt; } //离散傅里叶变换 void dft(complex F[], complex x[], int N) //X[]标识变换后频域,x[]为时域采样信号,下同 { float data_re[10]; float data_im[10]; complex temp; complex data; int k, n; for (int k = 0; k < N; k++) { F[k].re = 0; F[k].im = 0; for (int n = 0; n < N; n++) { temp.re = (float)cos(2 * pi * k * n / N); temp.im = -(float)sin(2 * pi * k * n / N); F[k] = complexadd(F[k], complexMult(x[n], temp)); data = complexadd(F[k], complexMult(x[n], temp)); data_re[n] = temp.re; data_im[n] = temp.im; } } } //离散傅里叶逆变换 void idft(complex X[], complex x[], int N) { complex temp; int k, n; for (int k = 0; k < N; k++) { x[k].re = 0; x[k].im = 0; for (int n = 0; n < N; n++) { temp.re = (float)cos(2 * pi * k * n / N); temp.im = (float)sin(2 * pi * k * n / N); x[k] = complexadd(x[k], complexMult(X[n], temp)); } x[k].re /= N; x[k].im /= N; } } #define N 10 int main() { complex samples[N], X[N], x[N]; //samples[]示例 for (int i = 0; i < N; i++) { samples[i].re = i; samples[i].im = 0; } dft(X, samples, N); printf("DFI:\n"); for (int i = 0; i < N; i++) { printf("(%f,%f)\n", X[i].re, X[i].im); } idft(X, x, N); printf("IDFI:\n"); for (int i = 0; i < N; i++) { printf("(%f,%f)\n", x[i].re, x[i].im); } }一维数组的傅里叶变换
运行结果如下
标签:temp,变换,float,C++,re,int,complex,im,傅里叶 From: https://www.cnblogs.com/lizhiqiang0204/p/17396929.html