FFT在Swift中使用加速

时间:2017-01-29 20:48:05

标签: swift fft

我正在尝试在swift中编写FFT代码以匹配Matlab FFT代码。

到目前为止,我注意到当“input.count”等于2 ^ n(其中n = 1,2,3,...)时,结果完全匹配。

但是,对于任意样本大小(“input.count”不等于2 ^ n),Swift和Matlab结果不匹配。

我用两个简单的例子粘贴下面的代码。

 import Accelerate

 public func fft(_ input: [Double]) -> ([Double],[Double]) {

 var real = [Double](input)

 var imaginary = [Double](repeating: 0.0, count: input.count)

 var splitComplex = DSPDoubleSplitComplex(realp: &real, imagp: &imaginary)

 let length = vDSP_Length(floor(log2(Float(input.count))))

 let radix = FFTRadix(kFFTRadix2)

 let weights = vDSP_create_fftsetupD(length, radix)

 vDSP_fft_zipD(weights!, &splitComplex, 1, length, FFTDirection(FFT_FORWARD))

 return (real, imaginary)
 }

// 2^N samples (WORKS; Matlab Output Same)
let (rl, img) = fft([1, 2, 3, 4, 5, 6, 7, 8])
print("REAL:", rl)
print(" ")
print("IMAG:", img)
print(" ")
// Swift Real: [36.0, -4.0, -4.0, -4.0, -4.0, -4.0, -4.0, -4.0]

// Matlab Real: [36, -4, -4, -4, -4, -4, -4, -4]

// Swift Imag: [0.0, 9.6568542494923797, 4.0, 1.6568542494923806, 0.0, -1.6568542494923806, -4.0, -9.6568542494923797]

// Matlab Imag: [0, 9.65685424949238, 4, 1.65685424949238, 0, -1.65685424949238, -4, -9.65685424949238]


// N samples (DOES NOT WORK; Matlab Output Different)
let (rl2, img2) = fft([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("REAL:", rl2)
print(" ")
print("IMAG:", img2)
print(" ")
// Swift Real: [36.0, -4.0, -4.0, -4.0, -4.0, -4.0, -4.0, -4.0, 9.0]

// Matlab Real: [45, -4.5, -4.5, -4.5, -4.5, -4.5, -4.5, -4.5, -4.5]

// Swift Imag: [0.0, 9.6568542494923797, 4.0, 1.6568542494923806, 0.0, -1.6568542494923806, -4.0, -9.6568542494923797, 0.0]

// Matlab Imag: [0, 12.3636483875458, 5.36289116667395, 2.59807621135332, 0.793471413188091, -0.793471413188091, -2.59807621135332, -5.36289116667395, -12.3636483875458]

0 个答案:

没有答案