InĀ [109]:
import math
# y=xåØ[-pi,pi]äøēå
éå¶ēŗ§ę°
def get_fourier1(n: int):
def f(x: float):
a = []
b = []
for i in range(1, n + 1):
a.append(0)
b.append(2 * (((-1) ** (i + 1)) / i))
res = a[0] / 2
for i in range(1, n + 1):
res += a[i - 1] * math.cos(i * x)
res += b[i - 1] * math.sin(i * x)
return res
return f
# y=x^2
def get_fourier2(n: int):
def f(x: float):
a = []
b = []
for i in range(1, n + 1):
a.append((4 * ((-1) ** i)) / (i ** 2))
b.append(0)
res = (2 * math.pi * math.pi / 3) / 2
for i in range(1, n + 1):
res += a[i - 1] * math.cos(i * x)
res += b[i - 1] * math.sin(i * x)
return res
return f
InĀ [110]:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 1000)
plt.plot(x, x, '-', label=r'$y=x$')
p = get_fourier1(10)
p_f = np.vectorize(p)
y_1 = p_f(x)
plt.plot(x, y_1, '-', label=r'$Fourier, n=10$')
plt.title('Fourier Expand')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid()
plt.show()
InĀ [111]:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-4, 4, 100)
y = x * x
plt.plot(x, y, '-', label=r'$y=x^2$')
# p = get_fourier2(2)
# p_f = np.vectorize(p)
# y_1 = p_f(x)
# plt.plot(x, y_1, '-', label=r'$Fourier, n=2$')
# p = get_fourier2(3)
# p_f = np.vectorize(p)
# y_1 = p_f(x)
# plt.plot(x, y_1, '-', label=r'$Fourier, n=3$')
p = get_fourier2(11)
p_f = np.vectorize(p)
y_1 = p_f(x)
plt.plot(x, y_1, '-', label=r'$Fourier, n=4$')
plt.title('Fourier Expand')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid()
plt.show()