DEV Community

kojix2
kojix2

Posted on

Fourier transform of Gaussian distribution in Ruby

Alt Text

require 'numo/narray'
require 'numo/pocketfft'
require 'gr/plot'

N = 4096
s = N / 256
pi = Math::PI

y = Array.new(N) do |i|
  x = i - N / 2
  Math.exp(-x**2 / (2.0 * s**2)) / (Math.sqrt(2 * pi) * s)
end

freq = Numo::DFloat.linspace(0,1,N+1)
freq[N/2..-1].inplace - 1.0
freq = freq[0..-2]

theory = freq.map { |k| Math.exp(-(2 * pi * k)**2 * s**2 / 2.0) }

x = freq
y = Numo::Pocketfft.fft(Numo::NArray.cast(y)).abs

GR.plot([x, y, 'bx'], [x, theory, 'r'], xlim: [-0.05, 0.05])
GR.savefig('gaussian.png')
Enter fullscreen mode Exit fullscreen mode

Top comments (0)