수학
푸리에 해석 : Parseval's 항등식 파이썬 코드
릿카。
2023. 4. 9. 22:56
이게 파세발 항등식입니다. 원래 domain과 frequency domain에서의 제곱 norm의 총합이 유지된다는 것인데, 일종의 에너지 보존이라 해석하기도 합니다.
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_parseval(n_terms):
return 0.25 + sum([(fourier_coefficients(n))**2 for n in range(1, n_terms + 1)])
# Calculate the mean square error
def error(func, truncated_func, n_terms, num_samples):
x = np.linspace(-1 * np.pi, 1 * np.pi, num_samples)
delta_x = 2*np.pi/num_samples
integral = delta_x * sum([func(xi)**2 for xi in x]).real
error = integral - truncated_func(n_terms)
return error
# Plot the mean square error for different numbers of terms
def plot_error(func, n_terms, num_samples):
mse_values = []
for n in range(1, n_terms + 1):
mse = error(func, truncated_parseval, n, num_samples)
mse_values.append(mse)
plt.plot(range(1, n_terms + 1), mse_values)
plt.xlabel('Number of terms')
plt.ylabel('error')
plt.title('Mean Square Convergence of Fourier Series for Sawtooth Function')
plt.legend()
plt.show()
n_terms = 100
num_samples = 100
plot_error(sawtooth_wave, n_terms, num_samples)
그래프가 이쁘게 나왔습니다 ^^