Skip to content

Instantly share code, notes, and snippets.

@dbr
Created August 26, 2011 10:28
Show Gist options
  • Save dbr/1173153 to your computer and use it in GitHub Desktop.
Save dbr/1173153 to your computer and use it in GitHub Desktop.
Discreet Fourier Transform in Python
"""Based on Javascript from
http://madebyevan.com/dft/
This may be wrong, but seems to do what I'd expect...
"""
from __future__ import division
import sys
import math
def ascii_plot(vals, width = 40):
mi = min(vals)
ma = max(vals)
print " " * (int(((0 - mi)/ma) * width)-1) + "0"
for x in vals:
print "#" * int((((x-mi) / ma) * width))
funcextent = 8
samplecount = 2**int(sys.argv[1])
def sample_func(f):
spatialX = [None for x in range(samplecount)]
spatialY = [None for x in range(samplecount)]
for i in range(samplecount):
spatialX[i] = (i / samplecount*2-1) * funcextent
spatialY[i] = f(spatialX[i])
return (spatialX, spatialY)
def box(x):
return int(x > -1) and int(x < 1)
def discreet_fourier_transform(spatialX, spatialY):
freqRealX = spatialX
freqImagX = spatialX
freqRealY = [None for x in range(samplecount)]
freqImagY = [None for x in range(samplecount)]
for i in range(samplecount):
ii = (i+samplecount/2) % samplecount
ii = int(ii)
freqRealY[ii] = freqImagY[ii] = 0
for j in range(samplecount):
jj = (j+samplecount / 2) % samplecount
jj = int(jj)
freqRealY[ii] += spatialY[jj] * math.cos(-2 * math.pi * i * j / samplecount)
freqImagY[ii] += spatialY[jj] * math.sin(-2 * math.pi * i * j / samplecount)
#ascii_plot(freqRealY)
spatialX, spatialY = sample_func(box)
discreet_fourier_transform(spatialX, spatialY)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment