这里直接给出一维离散傅里叶变换的公式,如下:
由欧拉公式可以进一步变形,得到以下形式,方便编写程序
单变量的傅里叶变换变换相对简单,为了更好地理解其含义,这里给出一个例子,相信看完这个例子,就会明白整个计算过程到底是怎么回事。
贴上实现代码
#include "stdafx.h"
#include<iostream>
#include<cmath>
#include<complex>
#include<ctime>
#define PI 3.14159
#define MAX 100
using namespace std;
void DFT1dim(complex<double>*Input, double Length, int flag)
{
complex<double> *Output = new complex<double>(Length);//新建一个与输入相同长度的数据指针
complex<double>wn;//旋转因子
for (int i = 0; i < Length; i++)
{
Output[i] = 0;
for (int j = 0; j < Length; j++)
{
wn = complex<double>(cos(2.0*PI*i*j / Length), sin(-flag * 2 * PI*i*j / Length));
Output[i] += Input[i] * wn;
}
if (Output[i].imag()>0)
cout <<i<<":" <<Output[i].real() << "+" << Output[i].imag() << "j" << endl;
else
cout <<i<<":"<< Output[i].real() << Output[i].imag() << "j" << endl;
}
if (flag == -1)
{
for (int i = 0; i < Length; i++)
{
Input[i] = Output[i] / Length;
}
}
delete[] Output;
}
complex<double> *SetInput(double size)
{
srand((double)time(0));
complex<double>* Output=new complex<double>[size];
for (int i = 0; i < size; i++)
{
Output[i] = complex<double>(rand()%MAX ,rand()%MAX );
}
return Output;
}
void Print( complex<double>*Output,double length)
{
for (int i = 0; i < length; i++)
{
/*cout << Output[i] <<endl;*/
if (Output[i].imag()>0)
cout << Output[i].real() << "+" << Output[i].imag() <<"j" <<endl;
else
cout<< Output[i].real() << Output[i].imag() <<"j"<< endl;
}
}
int main()
{
complex<double>*Input = SetInput(4);
cout << "时域内数据:" << endl;
Print(Input,4);
cout << "频域内数据:" << endl;
DFT1dim(Input,4,1);
return 0;
}
我这里采用的是随机生成的复数来进行傅里叶变换,如上面例子一样每个数据会对应输出一个在频域内的值,对这些值可以进行求幅值(模)以及相角。