Skip to content

Instantly share code, notes, and snippets.

@ZJUGuoShuai
Created July 28, 2023 15:04
Show Gist options
  • Save ZJUGuoShuai/3f328bac39167e4b8faed11881c1d385 to your computer and use it in GitHub Desktop.
Save ZJUGuoShuai/3f328bac39167e4b8faed11881c1d385 to your computer and use it in GitHub Desktop.
Swift 实现 DFT(原始算法)
import Cocoa
let input: [Float] = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
var output_real = Array<Float>(repeating: 0, count: 8)
var output_imag = Array<Float>(repeating: 0, count: 8)
for i in 0..<8 {
var real_sum: Float = 0.0
var imag_sum: Float = 0.0
for k in 0..<8 {
let phi: Float = -2.0 * Float.pi * Float(k)/8.0 * Float(i)
real_sum += input[k] * cos(phi)
imag_sum += input[k] * sin(phi)
}
output_real[i] = real_sum
output_imag[i] = imag_sum
}
print(output_real)
print(output_imag)
@ZJUGuoShuai
Copy link
Author

输出:

[28.0, -4.0000014, -3.999999, -4.000008, -4.0, -3.999992, -3.9999962, -3.9999962]
[0.0, 9.656853, 4.000001, 1.6568532, -7.5657417e-06, -1.6568551, -3.9999998, -9.656855]

与 NumPy 输出一致:

import numpy as np

x = np.arange(8)
y = np.fft.fft(x)
print(y)

NumPy 输出:

[28.+0.j         -4.+9.65685425j -4.+4.j         -4.+1.65685425j
 -4.+0.j         -4.-1.65685425j -4.-4.j         -4.-9.65685425j]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment