import numpy as np
import matplotlib.pyplot as plt
# Define the sawtooth function
def sawtooth_wave(x):
return (x % (2 * np.pi)) - np.pi
# Calculate the Fourier coefficients for the sawtooth function
def fourier_coefficients(n):
if n == 0:
return 0
else:
return 2*((-1)**n)/n - 2/n
# Calculate the truncated Fourier series
def truncated_fourier_series(x, N):
return 0.5 + sum([fourier_coefficients(n) * np.sin(n * x) for n in range(1, N + 1)])
# Calculate the mean square error
def mean_square_error(func, truncated_func, num_terms, num_samples):
x = np.linspace(-1 * np.pi, 1 * np.pi, num_samples)
delta_x = 2*np.pi/num_samples
mse = np.array([(func(xi)-truncated_func(xi, num_terms))**2 for xi in x]).real
mse_int = (1/(2*np.pi))*sum(mse)*delta_x
return mse_int
# Plot the mean square error for different numbers of terms
def plot_mean_square_error(func, num_coefficients, num_samples):
mse_values = []
for n in range(1, num_coefficients + 1):
mse = np.sum(mean_square_error(func, truncated_fourier_series, n, num_samples))
mse_values.append(mse)
plt.plot(range(1, num_coefficients + 1), mse_values)
plt.xlabel('Number of terms')
plt.ylabel('Mean square error')
plt.title('Mean Square Convergence of Fourier Series for Sawtooth Function')
plt.legend()
plt.show()
num_coefficients = 100
num_samples = 6000
plot_mean_square_error(sawtooth_wave, num_coefficients, num_samples)
음... 평균제곱에러가 수렴하긴 합니다! sawtooth 함수가 behavior가 안좋은건진 모르겠지만, 아무튼 0으로 수렴 성공!
참고로 다른 함수는 이렇게 나온다고 합니다.
Power Iteration - 가장 큰 고윳값을 가지는 고유벡터 (0) | 2025.02.04 |
---|---|
푸리에 해석 : Parseval's 항등식 파이썬 코드 (2) | 2023.04.09 |
푸리에 해석 : 리만-르베그 보조정리 파이썬코드 (0) | 2023.04.09 |
푸리에 변환 파이썬코드 - 디리클레, 체사로, 아벨 합 (0) | 2023.04.09 |
푸리에 해석 (2-5) : 체사로, 아벨 합 - 푸리에 급수의 응용 (0) | 2023.04.08 |
댓글 영역