실생활 데이터를 고등학교 수준의 수학으로 다루려면 최소제곱법을 이용한 근사 과정이 필요하다. 대학 과정이므로 고등학생들이 배우기는 어렵고 교사에게는 유용할 것 같다. 보통 “데이터를 삼차함수로 fitting한다”고 표현하곤 한다. 아래는 이를 위한 코드이다. fitting과 그 시각화를 모두 담았다.
import numpy as np
import matplotlib.pyplot as plt
# 주어진 데이터
xv = np.array([n for n in range(1,61)])
yv = np.array([
57, 70, 82, 68, 52, 47, 42, 40,40,40,40,30.9, 40, 40, 43,
58, 70, 82, 67, 52, 45, 42, 40,40,40,40,30.9, 40, 40, 42,
56.5, 70, 82, 68, 52, 45, 42, 40,40,40,39,30.9, 40, 40, 43,
57, 70, 82, 68, 52, 45, 42, 40,40,38,39,30.9, 40, 40, 44
])
# 주어진 함수 형태로 fitting하기 위해 sin(x) 값을 구함
sin_xv = np.sin(xv)
# 주어진 함수 형태로 fitting을 위한 행렬 생성 (range(1,32) : sinx(x)에 대한 31차 다항식으로 근사한다는 뜻)
X = np.column_stack([sin_xv**n for n in range(1, 32)])
# 다항식 계수 계산
coeff_fitting= np.linalg.lstsq(X, yv, rcond=None)[0]
print("Fitted coefficients:", coeff_fitting)
# fitting된 함수 생성
def custom_function(x):
return sum(coeff * np.sin(x)**n for n, coeff in enumerate(coeff_fitting, start=1))
# 데이터와 fitting된 함수 시각화
plt.scatter(xv, yv, label='Data')
x_vals = np.linspace(1, 59, 30) # 그래프를 부드럽게 만들기 위해 x 값 범위 지정
plt.plot(x_vals, custom_function(x_vals), color='red', label='Fitted Sine Curve')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Height of Wave according to Time')
plt.grid(True)
plt.show()
댓글 남기기