%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import math
def build_wave(fundamental_freq, a0, a_list, b_list):
return lambda x: a0 \
+ sum(map(lambda i: a_list[i] * math.cos(fundamental_freq * (i+1) * x), range(len(a_list)))) \
+ sum(map(lambda i: b_list[i] * math.sin(fundamental_freq * (i+1) * x), range(len(b_list))))
def graph_function(f, start, end, step=0.01, show_now=True):
x = np.arange(start, end, step)
plt.plot(x, map(f, x))
if show_now:
plt.show()
# y = 5 + 8 cos(x) + 4 cos(3x)
wave1 = build_wave(1, 5, [8, 0, 4], [])
graph_function(wave1, 0, 2*math.pi)
wave2 = build_wave(1, 0, [], [5,0,2])
graph_function(wave2, 0, 2*2*math.pi)
def integrate(f, start, end, step=0.01):
return sum(map(lambda x: f(x), np.arange(start, end, step)))*step
def fourier_transform(f, period, depth=10):
ang_velocity = 2*math.pi/period
a0 = (1/period) * integrate(f, 0, period)
a_list = []
b_list = []
for n in range(1,depth+1):
a_list.append( (2/period) * integrate(lambda x: f(x) * math.cos(n*x), 0, period) )
b_list.append( (2/period) * integrate(lambda x: f(x) * math.sin(n*x), 0, period) )
return {"ang_velocity":ang_velocity, "a0":a0, "a_list":a_list, "b_list":b_list}
def pretty_round(n):
n2 = round(float(n), 3)
return n2 if n2 != -0.0 else 0
def rename_zeros(d):
if type(d) == dict:
result = {}
for (k,v) in d.items():
result.update({k:rename_zeros(v)})
return result
elif type(d) == list:
return map(pretty_round, d)
elif type(d) in [int, float, long, complex, np.float64]:
return pretty_round(d)
else:
return d
result = fourier_transform(wave2, 2*math.pi, 3)
print rename_zeros(result)
{'a0': 0, 'ang_velocity': 1.0, 'a_list': [0, 0, 0], 'b_list': [5.0, 0, 2.0]}
graph_function(lambda x: wave2(x) - 2*math.sin(3*x), 0, 2*2*math.pi)
graph_function(lambda x: 5 * math.sin(x), 0, 2*2*math.pi)
result = fourier_transform(wave1, 2*math.pi, 3)
print rename_zeros(result)
{'a0': 5.018, 'ang_velocity': 1.0, 'a_list': [8.037, 0.037, 4.037], 'b_list': [0, 0, 0]}