离散傅里叶变换,逆变换(c语言)

#include <stdio.h>
#include <math.h>
#include "dfc.h"

#define pi 3.1415926

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 X[], complex x[], int N){ //X[]标识变换后频域,x[]为时域采样信号,下同
    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));

        }
        
    }
}
//离散傅里叶逆变换
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;
    }
}

  主程序:

 

#include <stdio.h>
#include "src/dfc.h"
#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);
    }  
}

  参考自知乎大佬:https://zhuanlan.zhihu.com/p/77347644   

上一篇:相同的class的各位object互为友元(friend)


下一篇:Python 数据类型 -- 数字(Number)