我目前正在尝试编写一些傅立叶变换算法。我从数学定义中描述的简单 DFT 算法开始:
public class DFT {
public static Complex[] Transform(Complex[] input) {
int N = input.Length;
Complex[] output = new Complex[N];
double arg = -2.0 * Math.PI / (double)N;
for (int n = 0; n < N; n++) {
output[n] = new Complex();
for (int k = 0; k < N; k++)
output[n] += input[k] * Complex.Polar(1, arg * (double)n * (double)k);
}
return output;
}
}
所以我用下面的代码测试了这个算法:
private int samplingFrequency = 120;
private int numberValues = 240;
private void doCalc(object sender, EventArgs e) {
Complex[] input = new Complex[numberValues];
Complex[] output = new Complex[numberValues];
double t = 0;
double y = 0;
for (int i = 0; i < numberValues; i++) {
t = (double)i / (double)samplingFrequency;
y = Math.Sin(2 * Math.PI * t);
input[i] = new Complex(y, 0);
}
output = DFT.Transform(input);
printFunc(input);
printAbs(output);
}
转换工作正常,但前提是 numberValues 是 samplingFrequency 的倍数(在本例中:120、240、360,...)。那是我对 240 个值的结果:
转换效果很好。
如果我试图计算 280 个值,我会得到以下结果:
如果更改计算值的数量,为什么会得到不正确的结果?我不确定我的问题是我的代码有问题还是对 DFT 的数学定义有误解。无论哪种方式,任何人都可以帮助我解决我的问题吗?谢谢。