Fourier series gives incorrect result for Odd function and others, but not on Even function

Viewed 26

I am trying to approximate the function f(x)=x^3 on [-1,1] using Fourier series.

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):

enter image description here

Which is wrong. I am highly confident that my code and the math should work fine. Another interesting fact: my code gives correct result for EVEN function.


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(32)]
bk_x_cube_list = [bk_x_cube(j) for j in range(1,32)]

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()
0 Answers
Related