I am trying to approximate the function $f(x)=x^{3}$ on $[-1,1]$ using Fourier series. Since $x^{3}$ is an odd function, we don't need to compute the coefficients $a_{k} = \int_{-1}^{1} x^{3} \cos(k \pi x) dx$. The coefficient $b_{k}$ is
$$ \int_{-1}^{1}x^{3} \sin(k \pi x) \: dx = -\frac{2}{\pi^{3} k^{3}} (\pi^{2} k^{2} - 6) \cos(k \pi)$$
Approximating using $n=30$ terms (30 coefficients), using Python and Matplotlib, I get the following result (red curve is $x^{3}$, blue is Fourier series):
Which is wrong. I am highly confident that my code should work fine. Another interesting fact: my code gives correct result for EVEN function.
I suspect there is a mathematical reasoning for this?
Code:
import math
import matplotlib.pyplot as plt
def ak_x_cube(k):
return 0
def bk_x_cube(k):
return (-2/((k*math.pi)**3))*( (k*math.pi)**2 - 6 )*math.cos(k*math.pi)
ak_x_cube_list = [ak_x_cube(j) for j in range(121)]
bk_x_cube_list = [bk_x_cube(j) for j in range(1,121)]
def fourier_x_cube(x, N):
result = (0.5*ak_x_cube_list[0])+sum([ (ak_x_cube_list[i+1]*math.cos((i+1)*math.pi*x)) + (bk_x_cube_list[i+1]*math.sin((i+1)*math.pi*x)) for i in range(round(N))])
return result
N = 5000
x = [-1 + (i/N)*2 for i in range(N+1)]
fig, ax = plt.subplots()
ax.plot(x, [fourier_x_cube(i, 30) for i in x], '-', color='black')
ax.plot(x, [i**3 for i in x], '-', color='red')
fig.show()
