Skip to content

Instantly share code, notes, and snippets.

@diegocasmo
Created March 6, 2017 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diegocasmo/43bbc581f12b051d6ebb31c1a96a8179 to your computer and use it in GitHub Desktop.
Save diegocasmo/43bbc581f12b051d6ebb31c1a96a8179 to your computer and use it in GitHub Desktop.
Implementation of the 'The Fast Fourier Transform Algorithm'
class FFT
# Input: n coefficients
# Output: Point-wise representation of the n coefficients
# Vec size must be a power of 2
def fft(vec)
return vec if vec.size <= 1
# Split A(x) into its odd and even powers
a_even = vec.each_with_index.select { |_, i| i.even? }.map { |i, _| i }
a_odd = vec.each_with_index.select { |_, i| i.odd? }.map { |i, _| i }
# Express A(x) in the form Ae(x^2) + xAo(x^2)
fft_even = fft(a_even) * 2
fft_odd = fft(a_odd) * 2
# Compute Ae(x^2) + xAo(x^2)
fft_even.zip(fft_odd).each_with_index.map { |(even, odd), i|
even + odd * omega(i, vec.size)
}
end
private
# Calculates (e ^ (2πik/n))
def omega(i, n)
Math::E ** Complex(0, -2 * Math::PI * i / n)
end
end
@diegocasmo
Copy link
Author

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