题目
f(t)是奇函数
积分定义方式求bn
import numpy as np
n = [1,2,3,4,5]
# 定义方式求bn
inte_s,inte_e = 0, np.pi
segNum = 1000000
t_points = np.linspace(inte_s,inte_e,segNum)
dis_bn = lambda i: np.sum(0.5*np.sin(i*t_points)*(inte_e-inte_s)/segNum)
print([(1-(-1)**i)/(2*i) for i in n])
print([dis_bn(i) for i in n])
结果如下
[1.0, 0.0, 0.3333333333333333, 0.0, 0.2]
[0.9999989999991774, 3.892893545362616e-16, 0.33333299999753263, 5.67757714215085e-17, 0.1999997999958876]
当n最大=1
import numpy as np
import matplotlib.pyplot as plt
_, ax = plt.subplots()
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.xlim(-5,5)
plt.ylim(-1.2,1.2)
start,end = -np.pi,np.pi
points = 300
t = np.linspace(start,end,points)
f_t = np.empty_like(t)
f_t[t<0] = -np.pi/4
f_t[t>0] = np.pi/4
plt.scatter(t,f_t,marker='.',s=1,c='b')
series_num = 1
f = lambda x: sum([np.sin(n*x)*(1-(-1)**n)/(2*n) for n in range(1,series_num+1)])
s_t = [f(i) for i in t]
plt.scatter(t,s_t,marker='.',s=1,c='r')
# 定义方式求bn
inte_s,inte_e = 0, np.pi
segNum = 10000
t_points = np.linspace(inte_s,inte_e,segNum)
dis_bn = lambda i: np.sum(0.5*np.sin(i*t_points)*(inte_e-inte_s)/segNum)
dis_f = lambda x: sum([np.sin(n*x)*dis_bn(n) for n in range(1,series_num+1)])
dis_st = [dis_f(i) for i in t]
plt.scatter(t,dis_st,marker='.',s=1,c='g')
print(s_t[0:3])
print(dis_st[0:3])
plt.legend(['f',f'fourier series_{series_num} of f',f'dis fourier series_{series_num} of f'])
plt.savefig('f.jpg')
[-1.2246467991473532e-16, -0.0210124511284756, -0.04201562375005738]
[-1.2245243243941147e-16, -0.02101034971052498, -0.04201142184208315]
当n最大=1000
[-6.174402573257526e-14, -0.797723992790085, -0.7901074952664077]
[-6.157155973065276e-14, -0.7975267965718601, -0.7899939672157446]