进行离散傅里叶变换后再执行离散傅里叶逆变换不会在Accelerate vDSP上产生原始值

时间:2019-02-24 15:06:19

标签: ios swift cocoa fft

我有一系列离散值。因此,我对输入部分没有任何虚构的值。我正在对这些值进行离散傅立叶变换并执行逆离散傅立叶变换,以获取相同的值。这样做的目的是测试Accelerate Framework的vDSP是否按预期工作,是否使文档有些废话,您必须自己弄清楚。

考虑以下代码

  lazy var DFTSetupForward: vDSP_DFT_Setup = {
    guard let setup = vDSP_DFT_zop_CreateSetupD(
      nil,
      vDSP_Length(self.numSamples),
      vDSP_DFT_Direction.FORWARD) else {
        fatalError("can't create vDSP_DFT_Setup")
    }
    return setup
  }()

  lazy var DFTSetupInverse: vDSP_DFT_Setup = {
    guard let setup = vDSP_DFT_zop_CreateSetupD(
      nil,
      vDSP_Length(self.numSamples),
      vDSP_DFT_Direction.INVERSE) else {
        fatalError("can't create vDSP_DFT_Setup")
    }
    return setup
  }()
 func discreteFourierTransform (_ valores:[Double] = []) -> ([Double], [Double]) {
    let numeroDados = valores.count

    let inputImag  = Array<Double>(repeating:0.0, count:numeroDados)
    var outputReal = Array<Double>(repeating:0.0, count:numeroDados)
    var outputImag = Array<Double>(repeating:0.0, count:numeroDados)

    vDSP_DFT_ExecuteD(DFTSetupForward, valores, inputImag, &outputReal, &outputImag)
    return (outputReal, outputImag)
  }


  // faz a DISCRETE FOURIER TRANSFORM DOUBLE
  // a saída corresponde aos vetores reais e imaginários
  func discreteFourierTransformInverse (_ valoresReais:[Double] = [],
                                        _ valoresImaginarios:[Double] = []) -> ([Double], [Double]) {
    let numeroDados = valoresReais.count

    var outputReal = Array<Double>(repeating:0.0, count:numeroDados)
    var outputImag = Array<Double>(repeating:0.0, count:numeroDados)

    vDSP_DFT_ExecuteD(DFTSetupInverse, valoresReais, valoresImaginarios, &outputReal, &outputImag)
    return (outputReal, outputImag)
  }

以及随后的这些呼叫

let (outputDFTreal, outputDFTImaginario ) = self.discreteFourierTransform(normalizedData)

let (sinalRealX, sinalImaginarioX ) = self.discreteFourierTransformInverse(outputDFTreal, outputDFTImaginario)

或换句话说,我正在从第一个let中获取傅立叶变换的结果,并将其注入到逆傅立叶变换中。我希望sinalRealX等于原始数据,在这种情况下为normalizedData,并且还希望signalImaginarioX都为零。

但是值完全不同!

这是怎么回事?

2 个答案:

答案 0 :(得分:3)

您不应期望IDFT返回归一化的值。您应该期望它返回原始的(预规范化)值,我相信它会这样做(在计算误差之内):

let fft = FFT()
let data = Array(stride(from: 0.0, to: Double(fft.numSamples), by: 1))
let normalizedData = data.map{ $0/Double(fft.numSamples) }
let (outputDFTreal, outputDFTImaginario ) = fft.discreteFourierTransform(normalizedData)
let (sinalRealX, sinalImaginarioX ) = fft.discreteFourierTransformInverse(outputDFTreal, outputDFTImaginario)
print(data)
print(sinalRealX)
print(sinalImaginarioX)

let zeros = Array(repeating: 0.0, count: data.count)
func avgerr(_ a: [Double], _ b: [Double]) -> Double {
    return zip(a, b).map { abs($0 - $1) }.reduce(0, +) / Double(a.count)
}

avgerr(data, sinalRealX)  // 2.442490654175344e-15
avgerr(zeros, sinalImaginarioX) // 2.602442788260593e-15

答案 1 :(得分:1)

浮点数是一个近似值。在双精度浮点算法中,相对于cos(0),10 ^ -19近似为零。

所以您确实在结果中得到了全零。