IndexOutOfRangeException在我试图实现FFT -固定,编辑:输出只是零,为什么
本文关键字:编辑 输出 为什么 固定 实现 FFT IndexOutOfRangeException | 更新日期: 2023-09-27 18:15:18
我是c#的初学者,我想实现以下FFT算法的伪代码:
function fft(n, f):
if (n = 1)
return f
else
g = fft(n/2, (f_0, f_2, ..., f_{n-2}))
u = fft(n/2, (f_1, f_3, ..., f_{n-1}))
for k = 0 to n/2 - 1
c_k = g_k + u_k*exp(-2*pi*i*k/n)
c_{k+n/2} = g_k-u_k*exp(-2*pi*i*k/n)
return c
我试图在c#中实现它,正如你所看到的:
public static class FFT
{
public static Complex[] fft(Complex[] f)
{
if (f.Length == 1)
{
return f;
}
else
{
Complex[] g = fft(even_indices(f));
Complex[] u = fft(odd_indices(f));
Complex[] c = new Complex[f.Length];
for (int k = 0; k < f.Length / 2 - 1; k++)
{
Complex w_k = u[k] * Complex.FromPolarCoordinates(1.0, -2 * Math.PI * k / f.Length);
c[k] = g[k] + w_k;
c[k + f.Length / 2] = g[k] - w_k;
}
return c;
}
}
private static Complex[] even_indices(Complex[] f)
{
Complex[] f_even = new Complex[f.Length / 2];
for (int i = 0; i < f.Length; i++)
{
if (i % 2 == 0)
{
f_even[i / 2] = f[i];
}
}
return f_even;
}
private static Complex[] odd_indices(Complex[] f)
{
Complex[] f_odd = new Complex[f.Length / 2];
for (int i = 0; i < f.Length; i++)
{
if (i % 2 == 1)
{
f_odd[(i-1)/2] = f[i];
}
}
return f_odd;
}
}
class Program
{
static void Main()
{
Complex[] test = { 1.0, 2.454167, 8.4567, 9.4564 };
var data = FFT.fft(test);
Console.WriteLine("FFT");
for (int i = 0; i < data.Length; i++)
{
Console.WriteLine(data[i]);
}
Console.ReadKey();
}
}
现在没有错误消息,它被完全编译。但是,输出是
FFT
(0,0) (0,0)(0, 0)
(0,0)这不是我想要的。这里出了什么问题?
再次感谢
Complex[] c = new Complex[f.Length / 2 - 1];
我将四舍五入,所以+ 1…f.Length == 2
将返回0数组长度
我希望下一行实际产生的错误:
c[k + f.Length / 2] = g[k] - u[k] * Complex.Exp(-w_k);
,你将len/2添加到k-index中,这将最终导致索引> length/2-1。(开发'c').
如果其余部分是正确的,你应该声明c为:
Complex[] c = new Complex[f.Length];
添加:在您的代码中,循环应该迭代到len/2-1,因此更改为:
for (int k = 0; k <= f.Length / 2 - 1; k++)