상세 컨텐츠

본문 제목

푸리에 해석 평균제곱수렴 파이썬 코드

수학

by 릿카。 2023. 4. 9. 22:54

본문

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으로 수렴 성공!

참고로 다른 함수는 이렇게 나온다고 합니다.

관련글 더보기

댓글 영역