Fast Fourier transform: Difference between revisions

m
m (→‎{{header|REXX}}: added/changed comments and whitespace, showed more decimal digits in the output, simplified the FMT function.)
 
(61 intermediate revisions by 32 users not shown)
Line 8:
and results in a sequence of equal length, again of complex numbers.
If you need to restrict yourself to real numbers, the output should
be the magnitude &nbsp; (i.e.: &nbsp; sqrt(re²<sup>2</sup> + im²<sup>2</sup>)) &nbsp; of the complex result.
 
The classic version is the recursive Cooley–Tukey FFT. [http://en.wikipedia.org/wiki/Cooley–Tukey_FFT_algorithm Wikipedia] has pseudo-code for that.
Further optimizations are possible but not required.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F fft(x)
V n = x.len
I n <= 1
R x
V even = fft(x[(0..).step(2)])
V odd = fft(x[(1..).step(2)])
V t = (0 .< n I/ 2).map(k -> exp(-2i * math:pi * k / @n) * @odd[k])
R (0 .< n I/ 2).map(k -> @even[k] + @t[k]) [+]
(0 .< n I/ 2).map(k -> @even[k] - @t[k])
 
print(fft([Complex(1.0), 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]).map(f -> ‘#1.3’.format(abs(f))).join(‘ ’))</syntaxhighlight>
 
{{out}}
<pre>
4.000 2.613 0.000 1.082 0.000 1.082 0.000 2.613
</pre>
 
=={{header|Ada}}==
Line 19 ⟶ 39:
a user instance of Ada.Numerics.Generic_Complex_Arrays.
 
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Numerics.Generic_Complex_Arrays;
Line 27 ⟶ 47:
use Complex_Arrays;
function Generic_FFT (X : Complex_Vector) return Complex_Vector;
</langsyntaxhighlight>
 
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Numerics;
with Ada.Numerics.Generic_Complex_Elementary_Functions;
Line 69 ⟶ 89:
return FFT (X, X'Length, 1);
end Generic_FFT;
</syntaxhighlight>
</lang>
 
Example:
 
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Numerics.Complex_Arrays; use Ada.Numerics.Complex_Arrays;
with Ada.Complex_Text_IO; use Ada.Complex_Text_IO;
Line 94 ⟶ 114:
end loop;
end;
</syntaxhighlight>
</lang>
 
{{out}}
Line 114 ⟶ 134:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.3.5 algol68g-2.3.5].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: Template.Fast_Fourier_transform.a68'''<langsyntaxhighlight lang="algol68">PRIO DICE = 9; # ideally = 11 #
 
OP DICE = ([]SCALAR in, INT step)[]SCALAR: (
Line 151 ⟶ 171:
coef
FI
);</langsyntaxhighlight>'''File: test.Fast_Fourier_transform.a68'''<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 172 ⟶ 192:
$"1¼ cycle wave: "$, compl array fmt, one and a quarter wave ft, $l$
))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 182 ⟶ 202:
{{trans|Fortran}}
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">fft←{
<lang APL>
1>k←2÷⍨N←⍴⍵:⍵
fft←{
0≠1|2⍟N:'Argument must be a power of 2 in length'
N←⍴⍵
N≤1:even←∇(N⍴0 1)/
odd←∇(N⍴1 0)/⍵
(1|2⍟N)≠0:'Argument must be a power of 2 in length'
even←fft(N⍴0 1)/⍵
odd←fft(N⍴1 0)/⍵
k←N÷2
T←even×*(0J¯2×(○1)×(¯1+⍳k)÷N)
(odd+T),odd-T
}</syntaxhighlight>
}
</lang>
 
'''Example:'''
<syntaxhighlight lang="apl"> fft 1 1 1 1 0 0 0 0</syntaxhighlight>
<lang APL>
fft 1 1 1 1 0 0 0 0
</lang>
 
{{out}}
<pre> 4 1J¯2.414213562 0 1J¯0.4142135624 0 1J0.4142135624
<pre>
0 1J2.414213562</pre>
4 1J¯2.414213562 0 1J¯0.4142135624 0 1J0.4142135624
0 1J2.414213562
</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> @% = &60A
DIM Complex{r#, i#}
Line 217 ⟶ 229:
FOR I% = 0 TO 7
READ in{(I%)}.r#
out{(I%)}.r# = in{(I%)}.r#
PRINT in{(I%)}.r# "," in{(I%)}.i#
NEXT
Line 252 ⟶ 265:
c.i# = i#
ENDPROC
</syntaxhighlight>
</lang>
{{out}}
<pre>Input (real, imag):
Line 277 ⟶ 290:
Note: array size is assumed to be power of 2 and not checked by code;
you can just pad it with 0 otherwise.
Also, <code>complex</code> is C99 standard.<langsyntaxhighlight Clang="c">
 
#include <stdio.h>
Line 330 ⟶ 343:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>Data: 1 1 1 1 0 0 0 0
Line 337 ⟶ 350:
===OS X / iOS===
OS X 10.7+ / iOS 4+
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <Accelerate/Accelerate.h>
 
Line 377 ⟶ 390:
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Data: 1 1 1 1 0 0 0 0
FFT : 4 (1, -2.41421) 0 (1, -0.414214) 0 (1, 0.414214) 0 (1, 2.41421) </pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Numerics;
using System.Linq;
using System.Diagnostics;
 
// Fast Fourier Transform in C#
public class Program {
 
/* Performs a Bit Reversal Algorithm on a postive integer
* for given number of bits
* e.g. 011 with 3 bits is reversed to 110 */
public static int BitReverse(int n, int bits) {
int reversedN = n;
int count = bits - 1;
 
n >>= 1;
while (n > 0) {
reversedN = (reversedN << 1) | (n & 1);
count--;
n >>= 1;
}
 
return ((reversedN << count) & ((1 << bits) - 1));
}
 
/* Uses Cooley-Tukey iterative in-place algorithm with radix-2 DIT case
* assumes no of points provided are a power of 2 */
public static void FFT(Complex[] buffer) {
#if false
int bits = (int)Math.Log(buffer.Length, 2);
for (int j = 1; j < buffer.Length / 2; j++) {
 
int swapPos = BitReverse(j, bits);
var temp = buffer[j];
buffer[j] = buffer[swapPos];
buffer[swapPos] = temp;
}
// Said Zandian
// The above section of the code is incorrect and does not work correctly and has two bugs.
// BUG 1
// The bug is that when you reach and index that was swapped previously it does swap it again
// Ex. binary value n = 0010 and Bits = 4 as input to BitReverse routine and returns 4. The code section above // swaps it. Cells 2 and 4 are swapped. just fine.
// now binary value n = 0010 and Bits = 4 as input to BitReverse routine and returns 2. The code Section
// swap it. Cells 4 and 2 are swapped. WROOOOONG
//
// Bug 2
// The code works on the half section of the cells. In the case of Bits = 4 it means that we are having 16 cells
// The code works on half the cells for (int j = 1; j < buffer.Length / 2; j++) buffer.Length returns 16
// and divide by 2 makes 8, so j goes from 1 to 7. This covers almost everything but what happened to 1011 value
// which must be swap with 1101. and this is the second bug.
//
// use the following corrected section of the code. I have seen this bug in other languages that uses bit
// reversal routine.
 
#else
for (int j = 1; j < buffer.Length; j++)
{
int swapPos = BitReverse(j, bits);
if (swapPos <= j)
{
continue;
}
var temp = buffer[j];
buffer[j] = buffer[swapPos];
buffer[swapPos] = temp;
}
 
// First the full length is used and 1011 value is swapped with 1101. Second if new swapPos is less than j
// then it means that swap was happen when j was the swapPos.
 
#endif
 
for (int N = 2; N <= buffer.Length; N <<= 1) {
for (int i = 0; i < buffer.Length; i += N) {
for (int k = 0; k < N / 2; k++) {
 
int evenIndex = i + k;
int oddIndex = i + k + (N / 2);
var even = buffer[evenIndex];
var odd = buffer[oddIndex];
 
double term = -2 * Math.PI * k / (double)N;
Complex exp = new Complex(Math.Cos(term), Math.Sin(term)) * odd;
 
buffer[evenIndex] = even + exp;
buffer[oddIndex] = even - exp;
 
}
}
}
}
 
public static void Main(string[] args) {
Complex[] input = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0};
FFT(input);
Console.WriteLine("Results:");
foreach (Complex c in input) {
Console.WriteLine(c);
}
}
}</syntaxhighlight>
{{out}}
<pre>
Results:
(4, 0)
(1, -2.41421356237309)
(0, 0)
(1, -0.414213562373095)
(0, 0)
(1, 0.414213562373095)
(0, 0)
(1, 2.41421356237309)
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <complex>
#include <iostream>
#include <valarray>
Line 507 ⟶ 637:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 531 ⟶ 661:
</pre>
 
=={{header|CCommon sharp|C#Lisp}}==
As the longer standing solution below didn't work out for me
<lang csharp>using System;
and I don't find it very nice, I want to give another one,
using System.Numerics;
that's not just a plain translation. Of course it could be
using System.Linq;
optimized in several ways.
using System.Diagnostics;
The function uses some non ASCII symbols for better readability
and condenses also the inverse part, by a keyword.
 
<syntaxhighlight lang="lisp">
// Fast Fourier Transform in C#
(defun fft (a &key (inverse nil) &aux (n (length a)))
public class Program {
"Perform the FFT recursively on input vector A.
 
Vector A must have length N of power of 2."
/* Performs a Bit Reversal Algorithm on a postive integer
(declare (type boolean inverse)
* for given number of bits
* e.g. 011 with 3 bits is(type reversed(integer to1) 110 */n))
(if (= n 1)
public static int BitReverse(int n, int bits) {
int reversedN = n;a
(let* int((n/2 count(/ =n bits - 1;2))
(2iπ/n (complex 0 (/ (* 2 pi) n (if inverse -1 1))))
 
n >>= 1; (⍵_n (exp 2iπ/n))
while (n >#c(1.0d0 0.0d0)) {
reversedN =(a0 (reversedNmake-array << 1n/2) | (n & 1);
count (a1 (make--;array n/2)))
(declare (type (integer 1) n >>= 1;/2)
(type (complex double-float) ⍵ ⍵_n))
}
(symbol-macrolet ((a0[j] (svref a0 j))
 
return ((reversedN << count) & ((1a1[j] << bits)(svref -a1 1j));
(a[i] (svref a i))
}
(a[i+1] (svref a (1+ i))))
 
(loop :for i :below (1- n) :by 2
/* Uses Cooley-Tukey iterative in-place algorithm with radix-2 DIT case
* assumes no of points provided are a power of 2 */:for j :from 0
:do (setf a0[j] a[i]
public static void FFT(Complex[] buffer) {
a1[j] a[i+1])))
 
(let ((â0 (fft a0 :inverse inverse))
int bits = (int)Math.Log(buffer.Length, 2);
for (int j = 1; j <(â1 buffer.Length(fft /a1 2;:inverse j++inverse)) {
(â (make-array n)))
 
(symbol-macrolet ((â[k] int swapPos = BitReverse(j,svref bitsâ k));
var temp = buffer[jk+n/2]; (svref â (+ k n/2)))
buffer[j] = buffer (â0[swapPosk]; (svref â0 k))
buffer (â1[swapPosk] = temp; (svref â1 k)))
} (loop :for k :below n/2
:do (setf â[k] (+ â0[k] (* ⍵ â1[k]))
 
â[k+n/2] (- â0[k] (* ⍵ â1[k])))
for (int N = 2; N <= buffer.Length; N <<= 1) {
for (int i = 0; i <:when buffer.Length; i += N) {inverse
for (int k = 0;:do (setf â[k] < N / 2; (/ â[k++)] {2)
â[k+n/2] (/ â[k+n/2] 2))
 
:do (setq int evenIndex(* = i + k;⍵_n))
int oddIndex = i + k +:finally (Nreturn / 2â)))))));
</syntaxhighlight>
var even = buffer[evenIndex];
From here on the old solution.
var odd = buffer[oddIndex];
<syntaxhighlight lang="lisp">
 
double term = -2 * Math.PI * k / (double)N;
Complex exp = new Complex(Math.Cos(term), Math.Sin(term)) * odd;
 
buffer[evenIndex] = even + exp;
buffer[oddIndex] = even - exp;
 
}
}
}
}
 
public static void Main(string[] args) {
Complex[] input = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0};
FFT(input);
Console.WriteLine("Results:");
foreach (Complex c in input) {
Console.WriteLine(c);
}
}
}</lang>
{{out}}
<pre>
Results:
(4, 0)
(1, -2.41421356237309)
(0, 0)
(1, -0.414213562373095)
(0, 0)
(1, 0.414213562373095)
(0, 0)
(1, 2.41421356237309)
</pre>
 
=={{header|Common Lisp}}==
<lang lisp>
;;; This is adapted from the Python sample; it uses lists for simplicity.
;;; Production code would use complex arrays (for compiler optimization).
Line 631 ⟶ 726:
;; finally, concatenate the sum and difference of the lists
(return (mapcan #'mapcar '(+ -) `(,ffta ,ffta) `(,aux ,aux)))))))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="lisp">
;;; Demonstrates printing an FFT in both rectangular and polar form:
CL-USER> (mapc (lambda (c) (format t "~&~6F~6@Fi = ~6Fe^~6@Fipi"
Line 652 ⟶ 747:
#C(0.9999999999999999D0 0.4142135623730949D0) #C(0.0D0 0.0D0)
#C(0.9999999999999997D0 2.414213562373095D0))
</syntaxhighlight>
</lang>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">require "complex"
 
def fft(x : Array(Int32 | Float64)) #: Array(Complex)
return [x[0].to_c] if x.size <= 1
even = fft(Array.new(x.size // 2) { |k| x[2 * k] })
odd = fft(Array.new(x.size // 2) { |k| x[2 * k + 1] })
c = Array.new(x.size // 2) { |k| Math.exp((-2 * Math::PI * k / x.size).i.exp) }
codd = Array.new(x.size // 2) { |k| c[k] * odd[k] }
return Array.new(x.size // 2) { |k| even[k] + codd[k] } + Array.new(x.size // 2) { |k| even[k] - codd[k] }
end
fft([1,1,1,1,0,0,0,0]).each{ |c| puts c }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 683 ⟶ 778:
=={{header|D}}==
===Standard Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.numeric;
 
[1.0, 1, 1, 1, 0, 0, 0, 0].fft.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[4+0i, 1-2.41421i, 0-0i, 1-0.414214i, 0+0i, 1+0.414214i, 0+0i, 1+2.41421i]</pre>
Line 693 ⟶ 788:
===creals Version===
Built-in complex numbers will be deprecated.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.math;
 
const(creal)[] fft(in creal[] x) pure /*nothrow*/ @safe {
Line 707 ⟶ 802:
void main() @safe {
[1.0L+0i, 1, 1, 1, 0, 0, 0, 0].fft.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[4+0i, 1+-2.41421i, 0+0i, 1+-0.414214i, 0+0i, 1+0.414214i, 0+0i, 1+2.41421i]</pre>
 
===Phobos Complex Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.math, std.complex;
 
auto fft(T)(in T[] x) pure /*nothrow @safe*/ {
Line 727 ⟶ 822:
void main() {
[1.0, 1, 1, 1, 0, 0, 0, 0].map!complex.array.fft.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[4+0i, 1-2.41421i, 0+0i, 1-0.414214i, 0+0i, 1+0.414214i, 0+0i, 1+2.41421i]</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.VarCmplx}}
{{libheader| System.Math}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Fast_Fourier_transform;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.VarCmplx,
System.Math;
 
function BitReverse(n: UInt64; bits: Integer): UInt64;
var
count, reversedN: UInt64;
begin
reversedN := n;
count := bits - 1;
 
n := n shr 1;
 
while n > 0 do
begin
reversedN := (reversedN shl 1) or (n and 1);
dec(count);
n := n shr 1;
end;
 
Result := ((reversedN shl count) and ((1 shl bits) - 1));
end;
 
procedure FFT(var buffer: TArray<Variant>);
var
j, bits: Integer;
tmp: Variant;
begin
bits := Trunc(Log2(length(buffer)));
 
for j := 1 to High(buffer) do
begin
var swapPos := BitReverse(j, bits);
if swapPos <= j then
Continue;
 
tmp := buffer[j];
buffer[j] := buffer[swapPos];
buffer[swapPos] := tmp;
end;
 
var N := 2;
while N <= Length(buffer) do
begin
var i := 0;
while i < Length(buffer) do
begin
for var k := 0 to N div 2 - 1 do
begin
var evenIndex := i + k;
var oddIndex := i + k + (N div 2);
var _even := buffer[evenIndex];
var _odd := buffer[oddIndex];
var term := -2 * PI * k / N;
var _exp := VarComplexCreate(Cos(term), Sin(term)) * _odd;
 
buffer[evenIndex] := _even + _exp;
buffer[oddIndex] := _even - _exp;
end;
i := i + N;
end;
N := N shl 1;
end;
 
end;
 
const
input: array of Double = [1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0];
 
var
inputc: TArray<Variant>;
 
begin
SetLength(inputc, length(input));
for var i := 0 to High(input) do
inputc[i] := VarComplexCreate(input[i]);
 
FFT(inputc);
 
for var c in inputc do
writeln(c);
readln;
end.</syntaxhighlight>
{{out}}
<pre>4 + 0i
1 - 2,41421356237309i
0 + 0i
1 - 0,414213562373095i
0 + 0i
1 + 0,414213562373095i
0 + 0i
1 + 2,41421356237309i</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(define -∏*2 (complex 0 (* -2 PI)))
 
Line 750 ⟶ 948:
→ #( 4+0i 1-2.414213562373095i 0+0i 1-0.4142135623730949i
0+0i 1+0.4142135623730949i 0+0i 1+2.414213562373095i)
</syntaxhighlight>
</lang>
 
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM FFT
 
Line 854 ⟶ 1,051:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 873 ⟶ 1,070:
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">
<lang Factor>
IN: USE math.transforms.fft
IN: { 1 1 1 1 0 0 0 0 } fft .
Line 886 ⟶ 1,083:
C{ 0.9999999999999997 2.414213562373095 }
}
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
<lang Fortran>
module fft_mod
implicit none
Line 947 ⟶ 1,144:
end do
 
end program test</langsyntaxhighlight>
{{out}}
<pre>
Line 958 ⟶ 1,155:
( 0.000000000000000, 0.000000000000000i )
( 1.000000000000000, 2.414213562373095i )</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">'Graphic fast Fourier transform demo,
'press any key for the next image.
'131072 samples: the FFT is fast indeed.
 
'screen resolution
const dW = 800, dH = 600
'--------------------------------------
type samples
declare constructor (byval p as integer)
 
'sw = 0 forward transform
'sw = 1 reverse transform
declare sub FFT (byval sw as integer)
 
'draw mythical birds
declare sub oiseau ()
 
'plot frequency and amplitude
declare sub famp ()
 
'plot transformed samples
declare sub bird ()
 
as double x(any), y(any)
as integer fl, m, n, n2
end type
 
constructor samples (byval p as integer)
m = p
'number of points
n = 1 shl p
n2 = n shr 1
'real and complex values
redim x(n - 1), y(n - 1)
end constructor
 
 
'--------------------------------------
'in-place complex-to-complex FFT adapted from
'[ http://paulbourke.net/miscellaneous/dft/ ]
 
sub samples.FFT (byval sw as integer)
dim as double c1, c2, t1, t2, u1, u2, v
dim as integer i, j = 0, k, L, l1, l2
 
'bit reversal sorting
for i = 0 to n - 2
if i < j then
swap x(i), x(j)
swap y(i), y(j)
end if
 
k = n2
while k <= j
j -= k: k shr= 1
wend
j += k
next i
 
'initial cosine & sine
c1 = -1.0
c2 = 0.0
'loop for each stage
l2 = 1
for L = 1 to m
l1 = l2: l2 shl= 1
 
'initial vertex
u1 = 1.0
u2 = 0.0
'loop for each sub DFT
for k = 1 to l1
'butterfly dance
for i = k - 1 to n - 1 step l2
j = i + l1
t1 = u1 * x(j) - u2 * y(j)
t2 = u1 * y(j) + u2 * x(j)
x(j) = x(i) - t1
y(j) = y(i) - t2
x(i) += t1
y(i) += t2
next i
 
'next polygon vertex
v = u1 * c1 - u2 * c2
u2 = u1 * c2 + u2 * c1
u1 = v
next k
 
'half-angle sine
c2 = sqr((1.0 - c1) * .5)
if sw = 0 then c2 = -c2
'half-angle cosine
c1 = sqr((1.0 + c1) * .5)
next L
 
'scaling for reverse transform
if sw then
for i = 0 to n - 1
x(i) /= n
y(i) /= n
next i
end if
end sub
 
'--------------------------------------
'Gumowski-Mira attractors "Oiseaux mythiques"
'[ http://www.atomosyd.net/spip.php?article98 ]
 
sub samples.oiseau
dim as double a, b, c, t, u, v, w
dim as integer dx, y0, dy, i, k
 
'bounded non-linearity
if fl then
a = -0.801
dx = 20: y0 =-1: dy = 12
else
a = -0.492
dx = 17: y0 =-3: dy = 14
end if
window (-dx, y0-dy)-(dx, y0+dy)
 
'dissipative coefficient
b = 0.967
c = 2 - 2 * a
 
u = 1: v = 0.517: w = 1
 
for i = 0 to n - 1
t = u
u = b * v + w
w = a * u + c * u * u / (1 + u * u)
v = w - t
 
'remove bias
t = u - 1.830
x(i) = t
y(i) = v
k = 5 + point(t, v)
pset (t, v), 1 + k mod 14
next i
sleep
end sub
 
'--------------------------------------
sub samples.famp
dim as double a, s, f = n / dW
dim as integer i, k
window
 
k = iif(fl, dW / 5, dW / 3)
for i = k to dW step k
line (i, 0)-(i, dH), 1
next i
 
a = 0
k = 0: s = f - 1
for i = 0 to n - 1
a += x(i) * x(i) + y(i) * y(i)
 
if i > s then
a = log(1 + a / f) * 0.045
if k then
line -(k, (1 - a) * dH), 15
else
pset(0, (1 - a) * dH), 15
end if
 
a = 0
k += 1: s += f
end if
next i
sleep
end sub
 
sub samples.bird
dim as integer dx, y0, dy, i, k
 
if fl then
dx = 20: y0 =-1: dy = 12
else
dx = 17: y0 =-3: dy = 14
end if
window (-dx, y0-dy)-(dx, y0+dy)
 
for i = 0 to n - 1
k = 2 + point(x(i), y(i))
pset (x(i), y(i)), 1 + k mod 14
next i
sleep
end sub
 
'main
'--------------------------------------
dim as integer i, p = 17
'n = 2 ^ p
dim as samples z = p
 
screenres dW, dH, 4, 1
 
for i = 0 to 1
z.fl = i
z.oiseau
 
'forward
z.FFT(0)
 
'amplitude plot with peaks at the
'± winding numbers of the orbits.
z.famp
 
'reverse
z.FFT(1)
 
z.bird
cls
next i
end</syntaxhighlight>
<b>(Images only)</b>
 
=={{header|Frink}}==
Frink has a built-in FFT function that can produce results based on different conventions. The following is not the default convention, but matches many of the other results in this page.
<syntaxhighlight lang="frink">a = FFT[[1,1,1,1,0,0,0,0], 1, -1]
println[joinln[format[a, 1, 5]]]
</syntaxhighlight>
{{out}}
<pre>
4.00000
( 1.00000 - 2.41421 i )
0.00000
( 1.00000 - 0.41421 i )
0.00000
( 1.00000 + 0.41421 i )
0.00000
( 1.00000 + 2.41421 i )
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Here an implementation with no optimization (O(n^2)).
# In GAP, E(n) = exp(2*i*pi/n), a primitive root of the unity.
 
Line 982 ⟶ 1,418:
 
InverseFourier(last);
# [ 1, 1, 1, 1, 0, 0, 0, 0 ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,013 ⟶ 1,449:
fmt.Printf("%8.4f\n", c)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,024 ⟶ 1,460:
( 0.0000 +0.0000i)
( 1.0000 +2.4142i)
</pre>
 
=={{header|Golfscript}}==
<syntaxhighlight lang="golfscript">#Cooley-Tukey
 
{.,.({[\.2%fft\(;2%fft@-1?-1\?-2?:w;.,,{w\?}%[\]zip{{*}*}%]zip.{{+}*}%\{{-}*}%+}{;}if}:fft;
 
[1 1 1 1 0 0 0 0]fft n*
</syntaxhighlight>
{{out}}
<pre>
4+0i
1.0000000000000002-2.414213562373095i
0.0+0.0i
0.9999999999999996-0.4142135623730949i
0+0i
1.0000000000000002+0.41421356237309515i
0.0+0.0i
1.0+2.414213562373095i
</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Complex
 
-- Cooley-Tukey
Line 1,043 ⟶ 1,498:
exp' k n = cis $ -2 * pi * (fromIntegral k) / (fromIntegral n)
main = mapM_ print $ fft [1,1,1,1,0,0,0,0]</langsyntaxhighlight>
 
{{out}}
Line 1,057 ⟶ 1,512:
 
=={{header|Idris}}==
<syntaxhighlight lang="text">module Main
 
import Data.Complex
Line 1,087 ⟶ 1,542:
 
main : IO()
main = traverse_ printLn $ fft [1,1,1,1,0,0,0,0]</langsyntaxhighlight>
 
{{out}}
Line 1,104 ⟶ 1,559:
Based on [[j:Essays/FFT]], with some simplifications -- sacrificing accuracy, optimizations and convenience which are not relevant to the task requirements, for clarity:
 
<langsyntaxhighlight lang="j">cube =: ($~ q:@#) :. ,
rou =: ^@j.@o.@(% #)@i.@-: NB. roots of unity
floop =: 4 : 'for_r. i.#$x do. (y=.{."1 y) ] x=.(+/x) ,&,:"r (-/x)*y end.'
fft =: ] floop&.cube rou@#</langsyntaxhighlight>
 
Example (first row of result is sine, second row of result is fft of the first row, (**+)&.+. cleans an irrelevant least significant bit of precision from the result so that it displays nicely):
 
<langsyntaxhighlight lang="j"> (**+)&.+. (,: fft) 1 o. 2p1*3r16 * i.16
0 0.92388 0.707107 0.382683 1 0.382683 0.707107 0.92388 0 0.92388 0.707107 0.382683 1 0.382683 0.707107 0.92388
0 0 0 0j8 0 0 0 0 0 0 0 0 0 0j8 0 0</langsyntaxhighlight>
 
Here is a representation of an example which appears in some of the other implementations, here:
<langsyntaxhighlight Jlang="j"> Re=: {.@+.@fft
Im=: {:@+.@fft
M=: 4#1 0
Line 1,124 ⟶ 1,579:
4 1 0 1 0 1 0 1
Im M
0 2.41421 0 0.414214 0 _0.414214 0 _2.41421</langsyntaxhighlight>
 
Note that Re and Im are not functions of 1 and 0 but are functions of the complete sequence.
Line 1,132 ⟶ 1,587:
=={{header|Java}}==
{{trans|C sharp}}
<langsyntaxhighlight lang="java">import static java.lang.Math.*;
 
public class FastFourierTransform {
Line 1,226 ⟶ 1,681:
return String.format("(%f,%f)", re, im);
}
}</langsyntaxhighlight>
 
<pre>Results:
Line 1,242 ⟶ 1,697:
variants on this page.
 
<langsyntaxhighlight lang="javascript">/*
complex fast fourier transform and inverse from
http://rosettacode.org/wiki/Fast_Fourier_transform#C.2B.2B
Line 1,307 ⟶ 1,762:
//test code
//console.log( cfft([1,1,1,1,0,0,0,0]) );
//console.log( icfft(cfft([1,1,1,1,0,0,0,0])) );</langsyntaxhighlight>
Very very basic Complex number that provides only the components
required by the code above.
<langsyntaxhighlight lang="javascript">/*
basic complex number arithmetic from
http://rosettacode.org/wiki/Fast_Fourier_transform#Scala
Line 1,359 ⟶ 1,814:
else
console.log(this.re.toString()+'+'+this.im.toString()+'j');
}</langsyntaxhighlight>
 
=={{header|jq}}==
Currently jq has no support for complex numbers, so the following implementation uses [x,y] to represent the complex number x+iy.
====Complex number arithmetic====
<syntaxhighlight lang="jq">
<lang jq>
# multiplication of real or complex numbers
def cmult(x; y):
Line 1,387 ⟶ 1,842:
 
# e(ix) = cos(x) + i sin(x)
def expi(x): [ (x|cos), (x|sin) ];</langsyntaxhighlight>
====FFT====
<langsyntaxhighlight lang="jq">def fft:
length as $N
| if $N <= 1 then .
Line 1,397 ⟶ 1,852:
| [ range(0; $N/2) | cplus($even[.]; cmult( expi(-2*$pi*./$N); $odd[.] )) ] +
[ range(0; $N/2) | cminus($even[.]; cmult( expi(-2*$pi*./$N); $odd[.] )) ]
end;</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="jq">[1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0] | fft
</syntaxhighlight>
</lang>
{{Out}}
[[4,-0],[1,-2.414213562373095],
Line 1,408 ⟶ 1,863:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using FFTW # or using DSP
Julia has a built-in FFT function:
 
<lang julia>fft([1,1,1,1,0,0,0,0])</lang>
fft([1,1,1,1,0,0,0,0])</syntaxhighlight>
{{out}}
<langsyntaxhighlight lang="julia">8-element Array{Complex{Float64},1}:
4.0+0.0im
1.0-2.41421im
Line 1,419 ⟶ 1,875:
1.0+0.414214im
0.0+0.0im
1.0+2.41421im</langsyntaxhighlight>
 
 
Since Julia version 0.7 and above, the FFT-function is maintained as part of the FFTW-library, requiring you to run the following steps first:
<lang julia>]add FFTW
using FFTW</lang>
An implementation of the radix-2 algorithm, which works for any vector for length that is a power of 2:
<langsyntaxhighlight lang="julia">
function fft(a)
y1 = Any[]; y2 = Any[]
Line 1,442 ⟶ 1,894:
return vcat(y1,y2)
end
</syntaxhighlight>
</lang>
 
=={{header|Klong}}==
<syntaxhighlight lang="k">fft::{ff2::{[n e o p t k];n::#x;
f::{p::2:#x;e::ff2(*'p);o::ff2({x@1}'p);k::-1;
t::{k::k+1;cmul(cexp(cdiv(cmul([0 -2];(k*pi),0);n,0));x)}'o;
(e cadd't),e csub't};
:[n<2;x;f(x)]};
n::#x;k::{(2^x)<n}{1+x}:~1;n#ff2({x,0}'x,&(2^k)-n)}</syntaxhighlight>
Example (rounding to 4 decimal digits):
<syntaxhighlight lang="k"> all(rndn(;4);fft([1 1 1 1 0 0 0 0]))</syntaxhighlight>
{{out}}
<pre>[[4.0 0.0]
[1.0 -2.4142]
[0.0 0.0]
[1.0 -0.4142]
[0.0 0.0]
[1.0 0.4142]
[0.0 0.0]
[1.0 2.4142]]</pre>
 
=={{header|Kotlin}}==
From Scala.
<langsyntaxhighlight lang="scala">import java.lang.Math.*
 
class Complex(val re: Double, val im: Double) {
Line 1,465 ⟶ 1,936:
private val a = "%1.3f".format(re)
private val b = "%1.3f".format(abs(im))
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="scala">object FFT {
fun fft(a: Array<Complex>) = _fft(a, Complex(0.0, 2.0), 1.0)
fun rfft(a: Array<Complex>) = _fft(a, Complex(0.0, -2.0), 2.0)
Line 1,494 ⟶ 1,965:
left + right
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="scala">fun Array<*>.println() = println(joinToString(prefix = "[", postfix = "]"))
 
fun main(args: Array<String>) {
Line 1,505 ⟶ 1,976:
a.println()
FFT.rfft(a).println()
}</langsyntaxhighlight>
 
{{out}}
Line 1,511 ⟶ 1,982:
[1.000, 1.000, 1.000, 1.000, 0.000, 2.000i, 0.000, 0.000]</pre>
 
=={{header|lambdatalkLambdatalk}}==
<langsyntaxhighlight lang="scheme">
 
1) the function fft
Line 1,623 ⟶ 2,094:
A more usefull example can be seen in http://lambdaway.free.fr/lambdaspeech/?view=zorg
 
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
P =8
S =int( log( P) /log( 2) +0.9999)
Line 1,732 ⟶ 2,203:
 
end
</syntaxhighlight>
</lang>
M Re( M) Im( M)
Line 1,745 ⟶ 2,216:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- operations on complex number
complex = {__mt={} }
Line 1,810 ⟶ 2,281:
data = toComplex{1, 1, 1, 1, 0, 0, 0, 0};
 
-- this works for old lua versions & luaJIT (depends on version!)
print("orig:", unpack(data))
-- print("fftorig:", unpack(fft(data)))</lang>
-- print("fft:", unpack(fft(data)))
 
-- Beginning with Lua 5.2 you have to write
print("orig:", table.unpack(data))
print("fft:", table.unpack(fft(data)))</syntaxhighlight>
 
=={{header|Maple}}==
Maple has a built-in package DiscreteTransforms, and FourierTransform and InverseFourierTransform are in the commands available from that package. The FourierTransform command offers an FFT method by default.
 
<syntaxhighlight lang="maple">
<lang Maple>
with( DiscreteTransforms ):
 
FourierTransform( <1,1,1,1,0,0,0,0>, normalization=none );
</syntaxhighlight>
</lang>
 
<pre>
Line 1,840 ⟶ 2,316:
</pre>
Optionally, the FFT may be performed inplace on a Vector of hardware double-precision complex floats.
<syntaxhighlight lang="maple">
<lang Maple>
v := Vector( [1,1,1,1,0,0,0,0], datatype=complex[8] ):
 
Line 1,846 ⟶ 2,322:
 
v;
</syntaxhighlight>
</lang>
 
<pre>
Line 1,865 ⟶ 2,341:
[1. + 2.41421356237309 I ]
</pre>
<syntaxhighlight lang="maple">
<lang Maple>
InverseFourierTransform( v, normalization=full, inplace ):
 
v;
</syntaxhighlight>
</lang>
 
<pre>
Line 1,896 ⟶ 2,372:
produce output that is consistent with most other FFT routines.
 
<syntaxhighlight lang="mathematica">
<lang Mathematica>
Fourier[{1,1,1,1,0,0,0,0}, FourierParameters->{1,-1}]
</syntaxhighlight>
</lang>
 
{{out}}
<pre>{4. + 0. I, 1. - 2.4142136 I, 0. + 0. I, 1. - 0.41421356 I, 0. + 0. I, 1. + 0.41421356 I, 0. + 0. I, 1. + 2.4142136 I}</pre>
 
Here is a user-space definition for good measure.
 
<syntaxhighlight lang="mathematica">fft[{x_}] := {N@x}
fft[l__] :=
Join[#, #] &@fft@l[[1 ;; ;; 2]] +
Exp[(-2 \[Pi] I)/Length@l (Range@Length@l - 1)] (Join[#, #] &@
fft[l[[2 ;; ;; 2]]])
 
fft[{1, 1, 1, 1, 0, 0, 0, 0}] // Column</syntaxhighlight>
{{out}}
<pre>4.
1. -2.41421 I
0. +0. I
1. -0.414214 I
0.
1. +0.414214 I
0. +0. I
1. +2.41421 I
</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 1,907 ⟶ 2,403:
Matlab/Octave have a builtin FFT function.
 
<langsyntaxhighlight MATLABlang="matlab"> fft([1,1,1,1,0,0,0,0]')
</syntaxhighlight>
</lang>
{{out}}
<pre>ans =
Line 1,922 ⟶ 2,418:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">load(fft)$
fft([1, 2, 3, 4]);
[2.5, -0.5 * %i - 0.5, -0.5, 0.5 * %i - 0.5]</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import math, complex, strutils
 
# Works with floats and complex numbers as input
Line 1,949 ⟶ 2,445:
let halfn = n div 2
 
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]):
echo formatFloat(abs(i), ffDecimal, 3)</langsyntaxhighlight>
{{out}}
<pre>4.000
2.613
-0.000
1.082
-0.000
1.082
-0.000
2.613</pre>
 
=={{header|OCaml}}==
This is a simple implementation of the Cooley-Tukey pseudo-code
<langsyntaxhighlight OCamllang="ocaml">open Complex
 
let fac k n =
Line 1,992 ⟶ 2,488:
let indata = [one;one;one;one;zero;zero;zero;zero] in
show indata;
show (fft indata)</langsyntaxhighlight>
 
{{out}}
Line 1,999 ⟶ 2,495:
(4.000000 0.000000) (1.000000 -2.414214) (0.000000 0.000000) (1.000000 -0.414214) (0.000000 0.000000) (1.000000 0.414214) (0.000000 0.000000) (1.000000 2.414214)
</pre>
 
 
=={{header|ooRexx}}==
{{trans|PL/I}} Output as shown in REXX
<langsyntaxhighlight lang="oorexx">Numeric Digits 16
list='1 1 1 1 0 0 0 0'
n=words(list)
Line 2,120 ⟶ 2,615:
else return "-" value~abs
 
::requires rxMath library</langsyntaxhighlight>
{{out}}
<pre>---data--- num real-part imaginary-part
Line 2,145 ⟶ 2,640:
=={{header|PARI/GP}}==
Naive implementation, using the same testcase as Ada:
<langsyntaxhighlight lang="parigp">FFT(v)=my(t=-2*Pi*I/#v,tt);vector(#v,k,tt=t*(k-1);sum(n=0,#v-1,v[n+1]*exp(tt*n)));
FFT([1,1,1,1,0,0,0,0])</langsyntaxhighlight>
{{out}}
<pre>[4.0000000000000000000000000000000000000, 1.0000000000000000000000000000000000000 - 2.4142135623730950488016887242096980786*I, 0.E-37 + 0.E-38*I, 1.0000000000000000000000000000000000000 - 0.41421356237309504880168872420969807856*I, 0.E-38 + 0.E-37*I, 0.99999999999999999999999999999999999997 + 0.41421356237309504880168872420969807860*I, 4.701977403289150032 E-38 + 0.E-38*I, 0.99999999999999999999999999999999999991 + 2.4142135623730950488016887242096980785*I]</pre>
differently, and even with "graphics"
<syntaxhighlight lang="parigp">install( FFTinit, Lp );
install( FFT, GG );
k = 7; N = 2 ^ k;
CIRC = FFTinit(k);
 
v = vector( N, i, 3 * sin( 1 * i*2*Pi/N) + sin( 33 *i*2*Pi/N) );
w = FFT(v, CIRC);
\\print("Signal");
\\plot( i = 1, N, v[ floor(i) ] );
print("Spectrum");
plot( i = 1, N / 2 , abs( w[floor(i)] ) * 2 / N );</syntaxhighlight>
{{out}}
<pre>Spectrum
3 |"'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''|
|: |
|: |
|: |
|: |
|: |
|: |
|: |
|: |
|: |
|: |
: : |
: : |
: : |
: : x |
: : : |
: : : |
: : : |
: : : : |
: : : : |
: : : : |
0 _,_______________________________,______________________________
1 64</pre>
 
=={{header|Pascal}}==
=== Recursive ===
{{works with|Free Pascal|3.2.0 }}
<syntaxhighlight lang="pascal">
PROGRAM RDFT;
 
(*)
 
Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64
The free and readable alternative at C/C++ speeds
compiles natively to almost any platform, including raspberry PI *
Can run independently from DELPHI / Lazarus
 
For debian Linux: apt -y install fpc
It contains a text IDE called fp
 
https://www.freepascal.org/advantage.var
 
(*)
 
USES
 
crt,
math,
sysutils,
ucomplex;
 
{$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined}
(*) Use for variants and ucomplex (*)
 
 
TYPE
 
table = array of complex;
 
 
 
PROCEDURE Split ( T: table ; EVENS: table; ODDS:table ) ;
 
VAR
k: integer ;
 
BEGIN
 
FOR k := 0 to Length ( T ) - 1 DO
IF Odd ( k ) THEN
ODDS [ k DIV 2 ] := T [ k ]
ELSE
 
EVENS [ k DIV 2 ] := T [ k ]
 
END;
 
 
 
PROCEDURE WriteCTable ( L: table ) ;
 
VAR
 
x :integer ;
 
BEGIN
 
FOR x := 0 to length ( L ) - 1 DO
 
BEGIN
 
Write ( Format ('%3.3g ' , [ L [ x ].re ] ) ) ;
 
IF ( L [ x ].im >= 0.0 ) THEN Write ( '+' ) ;
 
WriteLn ( Format ('%3.5gi' , [ L [ x ].im ] ) ) ;
 
END ;
 
END;
 
 
 
FUNCTION FFT ( L : table ): table ;
 
VAR
 
k : integer ;
N : integer ;
halfN : integer ;
E : table ;
Even : table ;
O : table ;
Odds : table ;
T : complex ;
 
BEGIN
 
N := length ( L ) ;
IF N < 2 THEN
EXIT ( L ) ;
 
halfN := ( N DIV 2 ) ;
 
SetLength ( E, halfN ) ;
SetLength ( O, halfN ) ;
Split ( L, E, O ) ;
SetLength ( L, 0 ) ;
SetLength ( Even, halfN ) ;
 
Even := FFT ( E ) ;
SetLength ( E , 0 ) ;
 
SetLength ( Odds, halfN ) ;
Odds := FFT ( O ) ;
SetLength ( O , 0 ) ;
SetLength ( L, N ) ;
FOR k := 0 to halfN - 1 DO
BEGIN
 
T := Cexp ( -2 * i * pi * k / N ) * Odds [ k ];
 
L [ k ] := Even [ k ] + T ;
 
L [ k + halfN ] := Even [ k ] - T ;
END ;
 
SetLength ( Even, 0 ) ;
SetLength ( Odds, 0 ) ;
FFT := L ;
 
END ;
 
 
 
VAR
 
Ar : array of complex ;
 
x : integer ;
 
BEGIN
 
 
 
SetLength ( Ar, 8 ) ;
 
FOR x := 0 TO 3 DO
BEGIN
 
Ar [ x ] := 1.0 ;
 
Ar [ x + 4 ] := 0.0 ;
END;
 
WriteCTable ( FFT ( Ar ) ) ;
SetLength ( Ar, 0 ) ;
 
 
 
END.
(*)
Output:
4 + 0i
1 -2.4142i
0 + 0i
1 -0.41421i
0 + 0i
1 +0.41421i
0 + 0i
1 +2.4142i
 
 
</syntaxhighlight>
JPD 2021/12/26
 
=={{header|Perl}}==
{{trans|Perl 6Raku}}
<langsyntaxhighlight Perllang="perl">use strict;
use warnings;
use Math::Complex;
Line 2,167 ⟶ 2,895:
}
 
print "$_\n" for fft qw(1 1 1 1 0 0 0 0);</langsyntaxhighlight>
{{out}}
<pre>4
Line 2,177 ⟶ 2,905:
0
1+2.41421356237309i</pre>
 
=={{header|Perl 6}}==
{{Works with|rakudo 2015-12}}
<lang perl6>sub fft {
return @_ if @_ == 1;
my @evn = fft( @_[0, 2 ... *] );
my @odd = fft( @_[1, 3 ... *] ) Z*
map &cis, (0, -tau / @_ ... *);
return flat @evn »+« @odd, @evn »-« @odd;
}
.say for fft <1 1 1 1 0 0 0 0>;</lang>
{{out}}
<pre>4+0i
1-2.41421356237309i
0+0i
1-0.414213562373095i
0+0i
1+0.414213562373095i
0+0i
1+2.41421356237309i</pre>
 
For the fun of it, here is a purely functional version:
 
<lang perl6>sub fft {
@_ == 1 ?? @_ !!
fft(@_[0,2...*]) «+«
fft(@_[1,3...*]) «*« map &cis, (0,-τ/@_...^-τ)
}</lang>
 
This particular version is numerically inaccurate though, because of the pi approximation. It is possible to fix it with the 'cisPi' function available in the TrigPi module:
 
<lang perl6>sub fft {
use TrigPi;
@_ == 1 ?? @_ !!
fft(@_[0,2...*]) «+«
fft(@_[1,3...*]) «*« map &cisPi, (0,-2/@_...^-2)
}</lang>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\FastFourierTransform.exw
-- demo\rosetta\FastFourierTransform.exw
-- =====================================
-- =====================================
--
--
-- Originally written by Robert Craig and posted to EuForum Dec 13, 2001
-- Originally written by Robert Craig and posted to EuForum Dec 13, 2001
--
--</span>
 
constant REAL = 1, IMAG = 2
<span style="color: #008080;">constant</span> <span style="color: #000000;">REAL</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">IMAG</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span>
 
type complex(sequence x)
<span style="color: #008080;">type</span> <span style="color: #004080;">complex</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
return length(x)=2 and atom(x[REAL]) and atom(x[IMAG])
<span style="color: #008080;">return</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">2</span> <span style="color: #008080;">and</span> <span style="color: #004080;">atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">REAL</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">and</span> <span style="color: #004080;">atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">IMAG</span><span style="color: #0000FF;">])</span>
end type
<span style="color: #008080;">end</span> <span style="color: #008080;">type</span>
 
function p2round(integer x)
<span style="color: #008080;">function</span> <span style="color: #000000;">p2round</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
-- rounds x up to a power of two
<span style="color: #000080;font-style:italic;">-- rounds x up to a power of two</span>
integer p = 1
<span style="color: #004080;">integer</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
while p<x do
<span style="color: #008080;">while</span> <span style="color: #000000;">p</span><span style="color: #0000FF;"><</span><span style="color: #000000;">x</span> <span style="color: #008080;">do</span>
p += p
<span style="color: #000000;">p</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">p</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
return p
<span style="color: #008080;">return</span> <span style="color: #000000;">p</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
function log2(atom x)
<span style="color: #008080;">function</span> <span style="color: #000000;">log_2</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
-- return log2 of x, or -1 if x is not a power of 2
<span style="color: #000080;font-style:italic;">-- return log2 of x, or -1 if x is not a power of 2</span>
if x>0 then
<span style="color: #008080;">if</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
integer p = -1
<span style="color: #004080;">integer</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
while floor(x)=x do
<span style="color: #008080;">while</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">x</span> <span style="color: #008080;">do</span>
x /= 2
<span style="color: #000000;">x</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">2</span>
p += 1
<span style="color: #000000;">p</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
if x=0.5 then
<span style="color: #008080;">if</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0.5</span> <span style="color: #008080;">then</span>
return p
<span style="color: #008080;">return</span> <span style="color: #000000;">p</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return -1
<span style="color: #008080;">return</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
function bitrev(sequence a)
<span style="color: #008080;">function</span> <span style="color: #000000;">bitrev</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
-- bitrev an array of complex numbers
<span style="color: #000080;font-style:italic;">-- bitrev an array of complex numbers</span>
integer j=1, n = length(a)
<span style="color: #004080;">integer</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
for i=1 to n-1 do
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
if i<j then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
{a[i],a[j]} = {a[j],a[i]}
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;"><</span><span style="color: #000000;">j</span> <span style="color: #008080;">then</span>
end if
<span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]}</span>
integer k = n/2
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
while k<j do
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span>
j -= k
<span style="color: #008080;">while</span> <span style="color: #000000;">k</span><span style="color: #0000FF;"><</span><span style="color: #000000;">j</span> <span style="color: #008080;">do</span>
k /= 2
<span style="color: #000000;">j</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">k</span>
end while
<span style="color: #000000;">k</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">2</span>
j = j+k
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end for
<span style="color: #000000;">j</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">+</span><span style="color: #000000;">k</span>
return a
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function cmult(complex arg1, complex arg2)
-- complex multiply
<span style="color: #008080;">function</span> <span style="color: #000000;">cmult</span><span style="color: #0000FF;">(</span><span style="color: #004080;">complex</span> <span style="color: #000000;">arg1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">complex</span> <span style="color: #000000;">arg2</span><span style="color: #0000FF;">)</span>
return {arg1[REAL]*arg2[REAL]-arg1[IMAG]*arg2[IMAG],
<span style="color: #000080;font-style:italic;">-- complex multiply </span>
arg1[REAL]*arg2[IMAG]+arg1[IMAG]*arg2[REAL]}
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">arg1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">REAL</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">arg2</span><span style="color: #0000FF;">[</span><span style="color: #000000;">REAL</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">arg1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">IMAG</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">arg2</span><span style="color: #0000FF;">[</span><span style="color: #000000;">IMAG</span><span style="color: #0000FF;">],</span>
end function
<span style="color: #000000;">arg1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">REAL</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">arg2</span><span style="color: #0000FF;">[</span><span style="color: #000000;">IMAG</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">arg1</span><span style="color: #0000FF;">[</span><span style="color: #000000;">IMAG</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">arg2</span><span style="color: #0000FF;">[</span><span style="color: #000000;">REAL</span><span style="color: #0000FF;">]}</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function ip_fft(sequence a)
-- perform an in-place fft on an array of complex numbers
<span style="color: #008080;">function</span> <span style="color: #000000;">ip_fft</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
-- that has already been bit reversed
<span style="color: #000080;font-style:italic;">-- perform an in-place fft on an array of complex numbers
integer n = length(a)
-- that has already been bit reversed</span>
integer ip, le, le1
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
complex u, w, t
<span style="color: #004080;">integer</span> <span style="color: #000000;">ip</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">le</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">le1</span>
 
<span style="color: #004080;">complex</span> <span style="color: #000000;">u</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t</span>
for l=1 to log2(n) do
le = power(2, l)
<span style="color: #008080;">for</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">log_2</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
le1 = le/2
<span style="color: #000000;">le</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">)</span>
u = {1, 0}
<span style="color: #000000;">le1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">le</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span>
w = {cos(PI/le1), sin(PI/le1)}
<span style="color: #000000;">u</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">}</span>
for j=1 to le1 do
<span style="color: #000000;">w</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">cos</span><span style="color: #0000FF;">(</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">/</span><span style="color: #000000;">le1</span><span style="color: #0000FF;">),</span> <span style="color: #7060A8;">sin</span><span style="color: #0000FF;">(</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">/</span><span style="color: #000000;">le1</span><span style="color: #0000FF;">)}</span>
for i=j to n by le do
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">le1</span> <span style="color: #008080;">do</span>
ip = i+le1
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">j</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">by</span> <span style="color: #000000;">le</span> <span style="color: #008080;">do</span>
t = cmult(a[ip], u)
<span style="color: #000000;">ip</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">le1</span>
a[ip] = sq_sub(a[i],t)
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cmult</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ip</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">u</span><span style="color: #0000FF;">)</span>
a[i] = sq_add(a[i],t)
<span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ip</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
u = cmult(u, w)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #000000;">u</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cmult</span><span style="color: #0000FF;">(</span><span style="color: #000000;">u</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return a
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function fft(sequence a)
integer n = length(a)
<span style="color: #008080;">function</span> <span style="color: #000000;">fft</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
if log2(n)=-1 then
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
puts(1, "input vector length is not a power of two, padded with 0's\n\n")
<span style="color: #008080;">if</span> <span style="color: #000000;">log_2</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
n = p2round(n)
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"input vector length is not a power of two, padded with 0's\n\n"</span><span style="color: #0000FF;">)</span>
-- pad with 0's
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">p2round</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
for j=length(a)+1 to n do
<span style="color: #000080;font-style:italic;">-- pad with 0's </span>
a = append(a,{0, 0})
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">})</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
a = ip_fft(bitrev(a))
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
-- reverse output from fft to switch +ve and -ve frequencies
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ip_fft</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bitrev</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))</span>
for i=2 to n/2 do
<span style="color: #000080;font-style:italic;">-- reverse output from fft to switch +ve and -ve frequencies</span>
integer j = n+2-i
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
{a[i],a[j]} = {a[j],a[i]}
<span style="color: #004080;">integer</span> <span style="color: #000000;">j</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span>
end for
<span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]}</span>
return a
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function ifft(sequence a)
integer n = length(a)
<span style="color: #008080;">function</span> <span style="color: #000000;">ifft</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
if log2(n)=-1 then ?9/0 end if -- (or as above?)
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
a = ip_fft(bitrev(a))
<span style="color: #008080;">if</span> <span style="color: #000000;">log_2</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- (or as above?)</span>
-- modifies results to get inverse fft
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ip_fft</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bitrev</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))</span>
for i=1 to n do
<span style="color: #000080;font-style:italic;">-- modifies results to get inverse fft</span>
a[i] = sq_div(a[i],n)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_div</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
return a
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
constant a = {{1, 0},
{1, 0},
<span style="color: #008080;">constant</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{1, 0},
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{1, 0},
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{0, 0},
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{0, 0},
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{0, 0},
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
{0, 0}}
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
 
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">}}</span>
printf(1, "Results of %d-point fft:\n\n", length(a))
ppOpt({pp_Nest,1,pp_IntFmt,"%10.6f",pp_FltFmt,"%10.6f"})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Results of %d-point fft:\n\n"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))</span>
pp(fft(a))
<span style="color: #7060A8;">ppOpt</span><span style="color: #0000FF;">({</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_IntFmt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%10.6f"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_FltFmt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%10.6f"</span><span style="color: #0000FF;">})</span>
printf(1, "\nResults of %d-point inverse fft (rounded to 6 d.p.):\n\n", length(a))
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fft</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))</span>
pp(ifft(fft(a)))</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"\nResults of %d-point inverse fft (rounded to 6 d.p.):\n\n"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ifft</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fft</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,375 ⟶ 3,068:
 
Complex Class File:
<syntaxhighlight lang="php">
<lang PHP>
<?php
 
Line 2,417 ⟶ 3,110:
}
 
</langsyntaxhighlight>
 
Example:
<syntaxhighlight lang="php">
<lang PHP>
<?php
 
Line 2,523 ⟶ 3,216:
echo PHP_EOL;
 
</syntaxhighlight>
</lang>
 
 
Line 2,564 ⟶ 3,257:
=={{header|PicoLisp}}==
{{works with|PicoLisp|3.1.0.3}}
<langsyntaxhighlight PicoLisplang="picolisp"># apt-get install libfftw3-dev
 
(scl 4)
Line 2,583 ⟶ 3,276:
(native "libfftw3.so" "fftw_destroy_plan" NIL P)
(native "libfftw3.so" "fftw_free" NIL Out)
(native "libfftw3.so" "fftw_free" NIL In) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(for R (fft '((1.0 0) (1.0 0) (1.0 0) (1.0 0) (0 0) (0 0) (0 0) (0 0)))
(tab (6 8)
(round (car R))
(round (cadr R)) ) )</langsyntaxhighlight>
{{out}}
<pre> 4.000 0.000
Line 2,600 ⟶ 3,293:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">test: PROCEDURE OPTIONS (MAIN, REORDER); /* Derived from Fortran Rosetta Code */
 
/* In-place Cooley-Tukey FFT */
Line 2,648 ⟶ 3,341:
end;
 
END test;</langsyntaxhighlight>
{{out}}
<pre> 4.000000000000+0.000000000000I
Line 2,658 ⟶ 3,351:
0.000000000000+0.000000000000I
0.999999999999+2.414213562373I</pre>
 
=={{header|POV-Ray}}==
<syntaxhighlight lang="pov-ray">
//cmd: +w0 +h0 -F -D
//Stockham algorithm
//Inspiration: http://wwwa.pikara.ne.jp/okojisan/otfft-en/optimization1.html
 
#version 3.7;
global_settings{ assumed_gamma 1.0 }
#default{ finish{ ambient 1 diffuse 0 emission 0}}
 
#macro Cstr(Comp)
concat("<",vstr(2, Comp,", ",0,-1),"j>")
#end
 
#macro CdebugArr(data)
#for(i,0, dimension_size(data, 1)-1)
#debug concat(Cstr(data[i]), "\n")
#end
#end
 
#macro R2C(Real) <Real, 0> #end
 
#macro CmultC(C1, C2) <C1.x * C2.x - C1.y * C2.y, C1.y * C2.x + C1.x * C2.y>#end
 
#macro Conjugate(Comp) <Comp.x, -Comp.y> #end
 
#macro IsPowOf2(X)
bitwise_and((X > 0), (bitwise_and(X, (X - 1)) = 0))
#end
 
#macro _FFT0(X, Y, N, Stride, EO)
#local M = div(N, 2);
#local Theta = 2 * pi / N;
#if(N = 1)
#if(EO)
#for(Q, 0, Stride-1)
#local Y[Q] = X[Q];
#end
#end
#else
#for(P, 0, M-1)
#local Fp = P * Theta;
#local Wp = <cos(Fp), -sin(Fp)>;
#for(Q, 0, Stride-1)
#local A = X[Q + Stride * (P + 0)];
#local B = X[Q + Stride * (P + M)];
#local Y[Q + Stride * (2 * P + 0)] = A + B;
#local Y[Q + Stride * (2 * P + 1)] = CmultC((A-B), Wp);
#end
#end
_FFT0(Y, X, div(N, 2), 2 * Stride, !EO)
#end
#end
 
#macro FFT(X)
#local N = dimension_size(X, 1);
#if(IsPowOf2(N)=0)
#error "length of input is not a power of two"
#end
#local Y = array[N];
_FFT0(X, Y, N, 1, false)
#undef Y
#end
 
#macro IFFT(X)
#local N = dimension_size(X,1);
#local Fn = R2C(1/N);
#for(P, 0, N-1)
#local X[P] = Conjugate(CmultC(X[P],Fn));
#end
#local Y = array[N];
_FFT0(X, Y, N, 1, false)
#undef Y
#for(P, 0, N-1)
#local X[P] = Conjugate(X[P]);
#end
#end
 
#declare data = array[8]{1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0};
#declare cdata = array[8];
#debug "\n\nData\n"
#for(i,0,dimension_size(data,1)-1)
#declare cdata[i] = R2C(data[i]);
#debug concat(Cstr(cdata[i]), "\n")
#end
 
#debug "\n\nFFT\n"
FFT(cdata)
CdebugArr(cdata)
 
#debug "\nPower\n"
#for(i,0,dimension_size(cdata,1)-1)
#debug concat(str(cdata[i].x * cdata[i].x + cdata[i].y * cdata[i].y, 0, -1), "\n")
#end
 
#debug "\nIFFT\n"
IFFT(cdata)
CdebugArr(cdata)
#debug "\n"
</syntaxhighlight>
 
{{out}}
<pre>
Data
<1.000000, 0.000000j>
<1.000000, 0.000000j>
<1.000000, 0.000000j>
<1.000000, 0.000000j>
<0.000000, 0.000000j>
<0.000000, 0.000000j>
<0.000000, 0.000000j>
<0.000000, 0.000000j>
 
FFT
<4.000000, 0.000000j>
<1.000000, -2.414214j>
<0.000000, 0.000000j>
<1.000000, -0.414214j>
<0.000000, 0.000000j>
<1.000000, 0.414214j>
<0.000000, 0.000000j>
<1.000000, 2.414214j>
 
Power
16.000000
6.828427
0.000000
1.171573
0.000000
1.171573
0.000000
6.828427
 
IFFT
<1.000000, 0.000000j>
<1.000000, -0.000000j>
<1.000000, -0.000000j>
<1.000000, -0.000000j>
<0.000000, -0.000000j>
<0.000000, 0.000000j>
<0.000000, 0.000000j>
<0.000000, 0.000000j>
</pre>
 
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">Function FFT($Arr){
$Len = $Arr.Count
 
If($Len -le 1){Return $Arr}
 
$Len_Over_2 = [Math]::Floor(($Len/2))
 
$Output = New-Object System.Numerics.Complex[] $Len
 
$EvenArr = @()
$OddArr = @()
 
For($i = 0; $i -lt $Len; $i++){
If($i % 2){
$OddArr+=$Arr[$i]
}Else{
$EvenArr+=$Arr[$i]
}
}
 
$Even = FFT($EvenArr)
$Odd = FFT($OddArr)
For($i = 0; $i -lt $Len_Over_2; $i++){
$Twiddle = [System.Numerics.Complex]::Exp([System.Numerics.Complex]::ImaginaryOne*[Math]::Pi*($i*-2/$Len))*$Odd[$i]
$Output[$i] = $Even[$i] + $Twiddle
$Output[$i+$Len_Over_2] = $Even[$i] - $Twiddle
}
Return $Output
}
</syntaxhighlight>
{{out}}
<pre>
PS C:\> FFT((1,1,1,1,0,0,0,0))
 
Real Imaginary Magnitude Phase
---- --------- --------- -----
4 0 4 0
1 -2.41421356237309 2.61312592975275 -1.17809724509617
0 0 0 0
1 -0.414213562373095 1.08239220029239 -0.392699081698724
0 0 0 0
1 0.414213562373095 1.08239220029239 0.392699081698724
0 0 0 0
1 2.41421356237309 2.61312592975275 1.17809724509617</pre>
 
=={{header|Prolog}}==
{{trans|Python}}Note: Similar algorithmically to the python example.
{{works with|SWI Prolog|Version 6.2.6 by Jan Wielemaker, University of Amsterdam}}
<langsyntaxhighlight lang="prolog">:- dynamic twiddles/2.
%_______________________________________________________________
% Arithemetic for complex numbers; only the needed rules
Line 2,699 ⟶ 3,586:
write(R), (I>=0, write('+'),fail;write(I)), write('j, '),
fail; write(']'), nl).
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,709 ⟶ 3,596:
=={{header|Python}}==
===Python: Recursive===
<langsyntaxhighlight lang="python">from cmath import exp, pi
 
def fft(x):
Line 2,721 ⟶ 3,608:
 
print( ' '.join("%5.3f" % abs(f)
for f in fft([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0])) )</langsyntaxhighlight>
 
{{out}}
Line 2,727 ⟶ 3,614:
 
===Python: Using module [http://numpy.scipy.org/ numpy]===
<langsyntaxhighlight lang="python">>>> from numpy.fft import fft
>>> from numpy import array
>>> a = array([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0])
>>> print( ' '.join("%5.3f" % abs(f) for f in fft(a)) )
4.000 2.613 0.000 1.082 0.000 1.082 0.000 2.613</langsyntaxhighlight>
 
=={{header|R}}==
The function "fft" is readily available in R
<langsyntaxhighlight Rlang="r">fft(c(1,1,1,1,0,0,0,0))</langsyntaxhighlight>
{{out}}
<pre>4+0.000000i 1-2.414214i 0+0.000000i 1-0.414214i 0+0.000000i 1+0.414214i 0+0.000000i 1+2.414214i</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
(array-fft (array #[1. 1. 1. 1. 0. 0. 0. 0.]))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,758 ⟶ 3,645:
0.9999999999999997+2.414213562373095i])
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo 2022-07}}
{{improve|raku|Not numerically accurate}}
<syntaxhighlight lang="raku" line>sub fft {
return @_ if @_ == 1;
my @evn = fft( @_[0, 2 ... *] );
my @odd = fft( @_[1, 3 ... *] ) Z*
map &cis, (0, -tau / @_ ... *);
return flat @evn »+« @odd, @evn »-« @odd;
}
 
.say for fft <1 1 1 1 0 0 0 0>;</syntaxhighlight>
{{out}}
<pre>4+0i
1-2.414213562373095i
0+0i
1-0.4142135623730949i
0+0i
0.9999999999999999+0.4142135623730949i
0+0i
0.9999999999999997+2.414213562373095i
</pre>
 
For the fun of it, here is a purely functional version:
 
<syntaxhighlight lang="raku" line>sub fft {
@_ == 1 ?? @_ !!
fft(@_[0,2...*]) «+«
fft(@_[1,3...*]) «*« map &cis, (0,-τ/@_...^-τ)
}</syntaxhighlight>
 
<!-- Not really helping now
This particular version is numerically inaccurate though, because of the pi approximation. It is possible to fix it with the 'cisPi' function available in the TrigPi module:
 
<syntaxhighlight lang="raku" line>sub fft {
use TrigPi;
@_ == 1 ?? @_ !!
fft(@_[0,2...*]) «+«
fft(@_[1,3...*]) «*« map &cisPi, (0,-2/@_...^-2)
}</syntaxhighlight>
-->
 
=={{header|REXX}}==
Line 2,771 ⟶ 3,701:
This REXX program also adds zero values &nbsp; if &nbsp; the number of data points in the list doesn't exactly equal to a
<br>power of two. &nbsp; This is known as &nbsp; ''zero-padding''.
<langsyntaxhighlight lang="rexx">/*REXX program performs a fast Fourier transform (FFT) on a set of complex numbers. */
numeric digits length( pi() ) - length(.) /*limited by the PI function result. */
arg data /*ARG verb uppercases the DATA from CL.*/
Line 2,838 ⟶ 3,768:
/*──────────────────────────────────────────────────────────────────────────────────────*/
pi: return 3.1415926535897932384626433832795028841971693993751058209749445923078164062862
r2r: return arg(1) // ( pi() * 2 ) /*reduce the radians to a unit circle. */</langsyntaxhighlight>
Programming note: &nbsp; the numeric precision (decimal digits) is only restricted by the number of decimal digits in the &nbsp;
<br>'''pi''' &nbsp; variable &nbsp; (which is defined in the penultimate assignment statement in the REXX program.
 
 
{{out|output|text=&nbsp; when using the default inputs of: &nbsp; &nbsp; <tt> 1 &nbsp; 1 &nbsp; 1 &nbsp; 1 &nbsp; 0 </tt>}}
<pre>
Line 2,866 ⟶ 3,800:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def fft(vec)
return vec if vec.size <= 1
evens_odds = vec.partition.with_index{|_,i| i.even?}
Line 2,875 ⟶ 3,809:
end
fft([1,1,1,1,0,0,0,0]).each{|c| puts "%9.6f %+9.6fi" % c.rect}</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,889 ⟶ 3,823:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">cnt = 8
sig = int(log(cnt) /log(2) +0.9999)
 
Line 2,988 ⟶ 3,922:
print " "; i;" ";using("##.#",rel(i));" ";img(i)
next i
end</langsyntaxhighlight>
<pre> Num real imag
0 4.0 0
Line 2,998 ⟶ 3,932:
6 0.0 0
7 1.0 2.41421356</pre>
 
=={{header|Rust}}==
{{trans|C}}
<langsyntaxhighlight lang="rust">extern crate num;
use num::complex::Complex;
use std::f64::consts::PI;
Line 3,060 ⟶ 3,995:
let output = fft(&input);
show("output:", &output);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,068 ⟶ 4,003:
4.0000+0.0000i, 1.0000-2.4142i, 0.0000+0.0000i, 1.0000-0.4142i, 0.0000+0.0000i, 1.0000+0.4142i, 0.0000+0.0000i, 1.0000+2.4142i
</pre>
 
=={{header|Scala}}==
{{libheader|Scala}}
Line 3,073 ⟶ 4,009:
{{works with|Scala|2.10.4}}
Imports and Complex arithmetic:
<langsyntaxhighlight Scalalang="scala">import scala.math.{ Pi, cos, sin, cosh, sinh, abs }
 
case class Complex(re: Double, im: Double) {
Line 3,097 ⟶ 4,033:
val r = (cosh(c.re) + sinh(c.re))
Complex(cos(c.im), sin(c.im)) * r
}</langsyntaxhighlight>
 
The FFT definition itself:
<langsyntaxhighlight Scalalang="scala">def _fft(cSeq: Seq[Complex], direction: Complex, scalar: Int): Seq[Complex] = {
if (cSeq.length == 1) {
return cSeq
Line 3,124 ⟶ 4,060:
 
def fft(cSeq: Seq[Complex]): Seq[Complex] = _fft(cSeq, Complex(0, 2), 1)
def rfft(cSeq: Seq[Complex]): Seq[Complex] = _fft(cSeq, Complex(0, -2), 2)</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight Scalalang="scala">val data = Seq(Complex(1,0), Complex(1,0), Complex(1,0), Complex(1,0),
Complex(0,0), Complex(0,2), Complex(0,0), Complex(0,0))
 
println(fft(data))
println(rfft(fft(data)))</langsyntaxhighlight>
 
{{out}}
<pre>Vector(4.000 + 2.000i, 2.414 + 1.000i, -2.000, 2.414 + 1.828i, 2.000i, -0.414 + 1.000i, 2.000, -0.414 - 3.828i)
Vector(1.000, 1.000, 1.000, 1.000, 0.000, 2.000i, 0.000, 0.000)</pre>
=={{header|Scheme}}==
{{works with|Chez Scheme}}
<syntaxhighlight lang="scheme">; Compute and return the FFT of the given input vector using the Cooley-Tukey Radix-2
; Decimation-in-Time (DIT) algorithm. The input is assumed to be a vector of complex
; numbers that is a power of two in length greater than zero.
 
(define fft-r2dit
=={{header|Scilab}}==
(lambda (in-vec)
; The constant ( -2 * pi * i ).
(define -2*pi*i (* -2.0i (atan 0 -1)))
; The Cooley-Tukey Radix-2 Decimation-in-Time (DIT) procedure.
(define fft-r2dit-aux
(lambda (vec start leng stride)
(if (= leng 1)
(vector (vector-ref vec start))
(let* ((leng/2 (truncate (/ leng 2)))
(evns (fft-r2dit-aux vec 0 leng/2 (* stride 2)))
(odds (fft-r2dit-aux vec stride leng/2 (* stride 2)))
(dft (make-vector leng)))
(do ((inx 0 (1+ inx)))
((>= inx leng/2) dft)
(let ((e (vector-ref evns inx))
(o (* (vector-ref odds inx) (exp (* inx (/ -2*pi*i leng))))))
(vector-set! dft inx (+ e o))
(vector-set! dft (+ inx leng/2) (- e o))))))))
; Call the Cooley-Tukey Radix-2 Decimation-in-Time (DIT) procedure w/ appropriate
; arguments as derived from the argument to the fft-r2dit procedure.
(fft-r2dit-aux in-vec 0 (vector-length in-vec) 1)))
 
; Test using a simple pulse.
Scilab has a builtin FFT function.
 
(let* ((inp (vector 1.0 1.0 1.0 1.0 0.0 0.0 0.0 0.0))
<lang Scilab>fft([1,1,1,1,0,0,0,0]')</lang>
(dft (fft-r2dit inp)))
(printf "In: ~a~%" inp)
(printf "DFT: ~a~%" dft))</syntaxhighlight>
{{out}}
<pre>
In: #(1.0 1.0 1.0 1.0 0.0 0.0 0.0 0.0)
DFT: #(4.0 1.0-2.414213562373095i 0.0-0.0i 1.0-0.4142135623730949i 0.0 1.0+0.41421356237309515i 0.0+0.0i 0.9999999999999997+2.414213562373095i)
</pre>
 
=={{header|SidefScilab}}==
{{trans|Perl}}
<lang ruby>func fft(arr) {
arr.len == 1 && return arr
 
Scilab has a builtin FFT function.
var evn = fft([arr[^arr -> grep { .is_even }]])
var odd = fft([arr[^arr -> grep { .is_odd }]])
var twd = (Num.tau.i / arr.len)
 
<syntaxhighlight lang="scilab">fft([1,1,1,1,0,0,0,0]')</syntaxhighlight>
^odd -> map {|n| odd[n] *= ::exp(twd * n)}
(evn »+« odd) + (evn »-« odd)
}
 
var cycles = 3
var sequence = 0..15
var wave = sequence.map {|n| ::sin(n * Num.tau / sequence.len * cycles) }
say "wave:#{wave.map{|w| '%6.3f' % w }.join(' ')}"
say "fft: #{fft(wave).map { '%6.3f' % .abs }.join(' ')}"</lang>
{{out}}
<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>
 
=={{header|SequenceL}}==
<langsyntaxhighlight lang="sequencel">import <Utilities/Complex.sl>;
import <Utilities/Math.sl>;
import <Utilities/Sequence.sl>;
Line 3,185 ⟶ 4,137:
x when n <= 1
else
complexAdd(top,z) ++ complexSubtract(top,z);</langsyntaxhighlight>
 
{{out}}
Line 3,191 ⟶ 4,143:
cmd:>fft(makeComplex([1,1,1,1,0,0,0,0],0))
[(Imaginary:0.00000000,Real:4.00000000),(Imaginary:-2.41421356,Real:1.00000000),(Imaginary:0.00000000,Real:0.00000000),(Imaginary:-0.41421356,Real:1.00000000),(Imaginary:0.00000000,Real:0.00000000),(Imaginary:0.41421356,Real:1.00000000),(Imaginary:0.00000000,Real:0.00000000),(Imaginary:2.41421356,Real:1.00000000)]
</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
<syntaxhighlight lang="ruby">func fft(arr) {
arr.len == 1 && return arr
 
var evn = fft([arr[^arr -> grep { .is_even }]])
var odd = fft([arr[^arr -> grep { .is_odd }]])
var twd = (Num.tau.i / arr.len)
 
^odd -> map {|n| odd[n] *= ::exp(twd * n)}
(evn »+« odd) + (evn »-« odd)
}
 
var cycles = 3
var sequence = 0..15
var wave = sequence.map {|n| ::sin(n * Num.tau / sequence.len * cycles) }
say "wave:#{wave.map{|w| '%6.3f' % w }.join(' ')}"
say "fft: #{fft(wave).map { '%6.3f' % .abs }.join(' ')}"</syntaxhighlight>
{{out}}
<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>
 
Line 3,198 ⟶ 4,174:
See the '''[https://www.stata.com/help.cgi?mf_fft fft function]''' in Mata help, and in the FAQ: [https://www.stata.com/support/faqs/mata/discrete-fast-fourier-transform/ How can I calculate the Fourier coefficients of a discretely sampled function in Stata?].
 
<syntaxhighlight lang="text">. mata
: a=1,2,3,4
: fft(a)
Line 3,205 ⟶ 4,181:
1 | 10 -2 - 2i -2 -2 + 2i |
+-----------------------------------------+
: end</langsyntaxhighlight>
 
=== fft command ===
Stata can also compute FFT using the undocumented '''fft''' command. Here is an example showing its syntax. A time variable must have been set prior to calling this command. Notice that in order to get the same result as Mata's fft() function, in both the input and the output variables the imaginary part must be passed '''first'''.
 
<langsyntaxhighlight lang="stata">clear
set obs 4
gen t=_n
Line 3,217 ⟶ 4,193:
tsset t
fft y x, gen(v u)
list u v, noobs</langsyntaxhighlight>
 
'''Output'''
Line 3,229 ⟶ 4,205:
| -2 2 |
+-----------------+</pre>
 
=={{header|Swift}}==
 
{{libheader|Swift Numerics}}
 
{{trans|Kotlin}}
 
<syntaxhighlight lang="swift">import Foundation
import Numerics
 
typealias Complex = Numerics.Complex<Double>
 
extension Complex {
var exp: Complex {
Complex(cos(imaginary), sin(imaginary)) * Complex(cosh(real), sinh(real))
}
 
var pretty: String {
let fmt = { String(format: "%1.3f", $0) }
let re = fmt(real)
let im = fmt(abs(imaginary))
 
if im == "0.000" {
return re
} else if re == "0.000" {
return im
} else if imaginary > 0 {
return re + " + " + im + "i"
} else {
return re + " - " + im + "i"
}
}
}
 
func fft(_ array: [Complex]) -> [Complex] { _fft(array, direction: Complex(0.0, 2.0), scalar: 1) }
func rfft(_ array: [Complex]) -> [Complex] { _fft(array, direction: Complex(0.0, -2.0), scalar: 2) }
 
private func _fft(_ arr: [Complex], direction: Complex, scalar: Double) -> [Complex] {
guard arr.count > 1 else {
return arr
}
 
let n = arr.count
let cScalar = Complex(scalar, 0)
 
precondition(n % 2 == 0, "The Cooley-Tukey FFT algorithm only works when the length of the input is even.")
 
var (evens, odds) = arr.lazy.enumerated().reduce(into: ([Complex](), [Complex]()), {res, cur in
if cur.offset & 1 == 0 {
res.0.append(cur.element)
} else {
res.1.append(cur.element)
}
})
 
evens = _fft(evens, direction: direction, scalar: scalar)
odds = _fft(odds, direction: direction, scalar: scalar)
 
let (left, right) = (0 ..< n / 2).map({i -> (Complex, Complex) in
let offset = (direction * Complex((.pi * Double(i) / Double(n)), 0)).exp * odds[i] / cScalar
let base = evens[i] / cScalar
 
return (base + offset, base - offset)
}).reduce(into: ([Complex](), [Complex]()), {res, cur in
res.0.append(cur.0)
res.1.append(cur.1)
})
return left + right
}
 
let dat = [Complex(1.0, 0.0), Complex(1.0, 0.0), Complex(1.0, 0.0), Complex(1.0, 0.0),
Complex(0.0, 0.0), Complex(0.0, 2.0), Complex(0.0, 0.0), Complex(0.0, 0.0)]
 
print(fft(dat).map({ $0.pretty }))
print(rfft(f).map({ $0.pretty }))</syntaxhighlight>
 
{{out}}
 
<pre>["4.000 + 2.000i", "2.414 + 1.000i", "-2.000", "2.414 + 1.828i", "2.000", "-0.414 + 1.000i", "2.000", "-0.414 - 3.828i"]
["1.000", "1.000", "1.000", "1.000", "0.000", "2.000", "0.000", "0.000"]</pre>
 
=={{header|SystemVerilog}}==
Line 3,236 ⟶ 4,293:
I could have written a more beautiful code by using non-blocking assignments in the bit_reverse_order function, but it could not be coded in a function, so FFT could not be implemented as a function as well.
 
<syntaxhighlight lang="systemverilog">
<lang SystemVerilog>
 
package math_pkg;
Line 3,324 ⟶ 4,381:
 
endclass
</syntaxhighlight>
</lang>
 
Now let's perform the standard test
<syntaxhighlight lang="systemverilog">
<lang SystemVerilog>
/// @Author: Alexandre Felipe (o.alexandre.felipe@gmail.com)
/// @Date: 2018-Jan-25
Line 3,351 ⟶ 4,408:
end
endmodule
</syntaxhighlight>
</lang>
By running the sanity test it outputs the following
<pre>
Line 3,377 ⟶ 4,434:
A more reliable test is to implement the Discrete Fourier Transform by its definition and compare the results obtained by FFT and by definition evaluation. For that let's create a class with a random data vector, and each time the vector is randomized the FFT is calculated and the output is compared by the result obtained by the definition.
 
<syntaxhighlight lang="systemverilog">
<lang SystemVerilog>
/// @Author: Alexandre Felipe (o.alexandre.felipe@gmail.com)
/// @Date: 2018-Jan-25
Line 3,430 ⟶ 4,487:
endfunction
endclass
</syntaxhighlight>
</lang>
 
Now let's create a code that tests the FFT with random inputs for different sizes.
Uses a generate block since the number of samples is a parameter and must be defined at compile time.
<syntaxhighlight lang="systemverilog">
<lang SystemVerilog>
/// @Author: Alexandre Felipe (o.alexandre.felipe@gmail.com)
/// @Date: 2018-Jan-25
Line 3,449 ⟶ 4,506:
endgenerate
endmodule
</syntaxhighlight>
</lang>
 
Simulating the fft_test_by_definition we get the following output:
Line 3,479 ⟶ 4,536:
{{tcllib|math::constants}}
{{tcllib|math::fourier}}
<langsyntaxhighlight lang="tcl">package require math::constants
package require math::fourier
 
Line 3,516 ⟶ 4,573:
# Convert to magnitudes for printing
set fft2 [waveMagnitude $fft]
printwave fft2</langsyntaxhighlight>
{{out}}
<pre>
Line 3,525 ⟶ 4,582:
=={{header|Ursala}}==
The [http://www.fftw.org <code>fftw</code> library] is callable from Ursala using the syntax <code>..u_fw_dft</code> for a one dimensional forward discrete Fourier transform operating on a list of complex numbers. Ordinarily the results are scaled so that the forward and reverse transforms are inverses of each other, but additional scaling can be performed as shown below to conform to convention.
<langsyntaxhighlight lang="ursala">#import nat
#import flo
 
Line 3,534 ⟶ 4,591:
#cast %jLW
 
t = (f,g)</langsyntaxhighlight>
{{out}}
<pre>(
Line 3,555 ⟶ 4,612:
0.000e+00+0.000e+00j,
1.000e+00+2.414e+00j>)</pre>
 
=={{header|VBA}}==
{{works with|VBA}}
{{trans|BBC_BASIC}}
Written and tested in Microsoft Visual Basic for Applications 7.1 under Office 365 Excel; but is probably useable under any recent version of VBA.
<syntaxhighlight lang="vba">Option Base 0
 
Private Type Complex
re As Double
im As Double
End Type
 
Private Function cmul(c1 As Complex, c2 As Complex) As Complex
Dim ret As Complex
ret.re = c1.re * c2.re - c1.im * c2.im
ret.im = c1.re * c2.im + c1.im * c2.re
cmul = ret
End Function
 
Public Sub FFT(buf() As Complex, out() As Complex, begin As Integer, step As Integer, N As Integer)
Dim i As Integer, t As Complex, c As Complex, v As Complex
If step < N Then
FFT out, buf, begin, 2 * step, N
FFT out, buf, begin + step, 2 * step, N
i = 0
While i < N
t.re = Cos(-WorksheetFunction.Pi() * i / N)
t.im = Sin(-WorksheetFunction.Pi() * i / N)
c = cmul(t, out(begin + i + step))
buf(begin + (i \ 2)).re = out(begin + i).re + c.re
buf(begin + (i \ 2)).im = out(begin + i).im + c.im
buf(begin + ((i + N) \ 2)).re = out(begin + i).re - c.re
buf(begin + ((i + N) \ 2)).im = out(begin + i).im - c.im
i = i + 2 * step
Wend
End If
End Sub
 
' --- test routines:
 
Private Sub show(r As Long, txt As String, buf() As Complex)
Dim i As Integer
r = r + 1
Cells(r, 1) = txt
For i = LBound(buf) To UBound(buf)
r = r + 1
Cells(r, 1) = buf(i).re: Cells(r, 2) = buf(i).im
Next
End Sub
 
Sub testFFT()
Dim buf(7) As Complex, out(7) As Complex
Dim r As Long, i As Integer
buf(0).re = 1: buf(1).re = 1: buf(2).re = 1: buf(3).re = 1
r = 0
show r, "Input (real, imag):", buf
FFT out, buf, 0, 1, 8
r = r + 1
show r, "Output (real, imag):", out
End Sub
</syntaxhighlight>
{{out}}
<pre>Input (real, imag):
1 0
1 0
1 0
1 0
0 0
0 0
0 0
0 0
 
Output (real, imag):
4 0
1 -2.414213562
0 0
1 -0.414213562
0 0
1 0.414213562
0 0
1 2.414213562</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import math.complex
import math
fn ditfft2(x []f64, mut y []Complex, n int, s int) {
if n == 1 {
y[0] = complex(x[0], 0)
return
}
ditfft2(x, mut y, n/2, 2*s)
ditfft2(x[s..], mut y[n/2..], n/2, 2*s)
for k := 0; k < n/2; k++ {
tf := cmplx.Rect(1, -2*math.pi*f64(k)/f64(n)) * y[k+n/2]
y[k], y[k+n/2] = y[k]+tf, y[k]-tf
}
}
fn main() {
x := [f64(1), 1, 1, 1, 0, 0, 0, 0]
mut y := []Complex{len: x.len}
ditfft2(x, mut y, x.len, 1)
for c in y {
println("${c:8.4f}")
}
}</syntaxhighlight>
 
{{out}}
<pre>
i d
2 3.21851142
3 4.38567760
4 4.60094928
5 4.65513050
6 4.66611195
7 4.66854858
8 4.66906066
9 4.66917155
10 4.66919515
11 4.66920026
12 4.66920098
13 4.66920537
</pre>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-complex}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./complex" for Complex
import "./fmt" for Fmt
 
var ditfft2 // recursive
ditfft2 = Fn.new {|x, y, n, s|
if (n == 1) {
y[0] = Complex.new(x[0], 0)
return
}
var hn = (n/2).floor
ditfft2.call(x, y, hn, 2*s)
var z = y[hn..-1]
ditfft2.call(x[s..-1], z, hn, 2*s)
for (i in hn...y.count) y[i] = z[i-hn]
for (k in 0...hn) {
var tf = Complex.fromPolar(1, -2 * Num.pi * k / n) * y[k + hn]
var t = y[k]
y[k] = y[k] + tf
y[k + hn] = t - tf
}
}
 
var x = [1, 1, 1, 1, 0, 0, 0, 0]
var y = List.filled(x.count, null)
for (i in 0...y.count) y[i] = Complex.zero
ditfft2.call(x, y, x.count, 1)
for (c in y) Fmt.print("$6.4z", c)</syntaxhighlight>
 
{{out}}
<pre>
4.0000 + 0.0000i
1.0000 - 2.4142i
0.0000 + 0.0000i
1.0000 - 0.4142i
0.0000 + 0.0000i
1.0000 + 0.4142i
0.0000 + 0.0000i
1.0000 + 2.4142i
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
v:=GSL.ZVector(8).set(1,1,1,1);
GSL.FFT(v).toList().concat("\n").println(); // in place</langsyntaxhighlight>
{{out}}
<pre>
122

edits