This is a very simple code that expresses a function in terms of Trigonometric Fourier Series and generates a animation based on the harmonics. I would like to know some ways to improve the performance of the code and its readability. I believe that any question about the mathematical part can be answered here.
Here's the whole code:
import matplotlib.pyplot as plt
from numpy import sin, cos, pi, linspace
from scipy.integrate import quad as integral
from celluloid import Camera
def desired_function(t):
return t**2
def a_zero(function, half_period, inferior_limit, superior_limit):
return (1/(2*half_period)) * integral(function, inferior_limit, superior_limit)[0]
def a_k(k, half_period, inferior_limit, superior_limit):
return (1/half_period) * integral(lambda x: desired_function(x) * cos(x * k * (pi / half_period)), inferior_limit, superior_limit)[0]
def b_k(k, half_period, inferior_limit, superior_limit):
return (1/half_period) * integral(lambda x: desired_function(x) * sin(x * k * (pi / half_period)), inferior_limit, superior_limit)[0]
def main():
fig = plt.figure()
camera = Camera(fig)
inferior_limit, superior_limit = -pi, pi
half_period = (superior_limit - inferior_limit) / 2
x = linspace(inferior_limit, superior_limit, 1000)
f = a_zero(desired_function, half_period, inferior_limit, superior_limit)
# The sum ranging from 1 to total_k
total_k = 30
for k in range(1, total_k+1):
f += a_k(k, half_period, inferior_limit, superior_limit)*cos(k*x*(pi/half_period)) +\
b_k(k, half_period, inferior_limit, superior_limit)*sin(k*x*(pi/half_period))
plt.plot(x, desired_function(x), color='k')
plt.plot(x, f, label=f'k = {k}')
camera.snap()
animation = camera.animate()
plt.close()
animation.save('animation.gif')
if __name__ == '__main__':
main()
And my biggest issue is this for loop being used as a Σ, is there a more elegant way to express this?
# The sum ranging from 1 to total_k
total_k = 30
for k in range(1, total_k+1):
f += a_k(k, half_period, inferior_limit, superior_limit)*cos(k*x*(pi/half_period)) +\
b_k(k, half_period, inferior_limit, superior_limit)*sin(k*x*(pi/half_period))
Thanks in advance to anyone who takes the time to help me with this!