Fast Fourier transform: Difference between revisions
Content added Content deleted
Line 1,929: | Line 1,929: | ||
{{trans|Python}} |
{{trans|Python}} |
||
<lang nim>import math, complex, strutils |
<lang nim>import math, complex, strutils |
||
proc toComplex(x: float): TComplex = result.re = x |
|||
proc toComplex(x: TComplex): TComplex = x |
|||
# Works with floats and complex numbers as input |
# Works with floats and complex numbers as input |
||
proc fft[T](x: openarray[T]): seq[ |
proc fft[T: float | Complex[float]](x: openarray[T]): seq[Complex[float]] = |
||
let n = x.len |
let n = x.len |
||
⚫ | |||
result = newSeq[TComplex]() |
|||
⚫ | |||
result.newSeq(n) |
|||
if n == 1: |
|||
result[0] = (when T is float: complex(x[0]) else: x[0]) |
|||
return |
return |
||
var evens, odds = newSeq[T]() |
var evens, odds = newSeq[T]() |
||
for i, v in x: |
for i, v in x: |
||
Line 1,946: | Line 1,947: | ||
var (even, odd) = (fft(evens), fft(odds)) |
var (even, odd) = (fft(evens), fft(odds)) |
||
let halfn = n div 2 |
|||
result.add(even[k] + exp((0.0, -2*pi*float(k)/float(n))) * odd[k]) |
|||
for k in 0 .. < |
for k in 0 .. < halfn: |
||
let a = exp(complex(0.0, -2 * Pi* float(k) / float(n))) * odd[k] |
|||
result[k] = even[k] + a |
|||
result[k + halfn] = even[k] - a |
|||
for i in fft(@[1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]): |
for i in fft(@[1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]): |