Fast Fourier transform: Difference between revisions

Content added Content deleted
(Change {{draft task}} to {{task}})
(→‎Tcl: Added implementation)
Line 64: Line 64:
2.44249065e-15 +8.00062775e+00j,
2.44249065e-15 +8.00062775e+00j,
0.00000000e+00 +0.00000000e+00j, 2.33146835e-15 -1.28750059e-03j])</lang>
0.00000000e+00 +0.00000000e+00j, 2.33146835e-15 -1.28750059e-03j])</lang>

=={{header|Tcl}}==
{{tcllib|math::constants}}
{{tcllib|math::fourier}}
<lang tcl>package require math::constants
package require math::fourier

math::constants::constants pi
# Helper functions
proc wave {samples cycles} {
global pi
set wave {}
set factor [expr {2*$pi * $cycles / $samples}]
for {set i 0} {$i < $samples} {incr i} {
lappend wave [expr {sin($factor * $i)}]
}
return $wave
}
proc printwave {waveName {format "%7.3f"}} {
upvar 1 $waveName wave
set out [format "%-6s" ${waveName}:]
foreach value $wave {
append out [format $format $value]
}
puts $out
}
proc waveMagnitude {wave} {
set out {}
foreach value $wave {
lassign $value re im
lappend out [expr {hypot($re, $im)}]
}
return $out
}

set wave [wave 16 3]
printwave wave
# Uses FFT if input length is power of 2, and a less efficient algorithm otherwise
set fft [waveMagnitude [math::fourier::dft $wave]]
printwave fft</lang>
Output:
<pre>
wave: 0.000 0.924 0.707 -0.383 -1.000 -0.383 0.707 0.924 0.000 -0.924 -0.707 0.383 1.000 0.383 -0.707 -0.924
fft: 0.000 0.000 0.000 8.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 8.000 0.000 0.000
</pre>