728x90
Sin, Cos, 자연로그 함수 테일러 전개식을 Python으로 구현해보자
Sin, Cos, 자연로그 함수의 테일러 전개는 다음과 같다.
import math
import numpy as np
import matplotlib.pyplot as plt
# n 차수 Taylor Series
# Sin(x)
def func_sin( x,n ) :
approx_sin = 0
for i in range(n):
coef = (-1)**i
denom = math.factorial(2*i+1)
num = x**(2*i+1)
approx_sin += coef * num / denom
return approx_sin
# Cos(x)
def func_cos( x, n ) :
approx_cos = 0;
for i in range (n) :
coef = (-1)**i
denom = math.factorial(2*i)
num = x**(2*i)
approx_cos += coef * num / denom
return approx_cos
# e^x
def func_e( x, n ) :
approx_e = 0
for i in range( n ) :
coef = 1
denom = math.factorial( i )
num = x**i
approx_e += coef * num / denom
return approx_e
Taylor Series - 3 Terms Sin, Cos 함수 그래프를 그려보자
함수가 만들었다면 3 차수 Taylor 함수 그래프를 그려보자.
# 그래프로 나타내보자
angles = np.arange( -2*np.pi, 2*np.pi, 0.1)
# 진짜 sin함수인 p_sin 과 우리가 만든 테일러 급수 t_sin
p_sin = np.sin(angles)
t_sin = [func_sin(angle,3) for angle in angles]
# 진짜 cos수인 p_cos 과 우리가 만든 테일러 급수 t_cos
p_cos = np.cos(angles)
t_cos = [func_cos(angle,3) for angle in angles]
# Sin 함수
fig, g1 = plt.subplots()
g1.plot(angles,p_sin)
g1.plot(angles,t_sin)
g1.set_ylim([-5,5])
g1.legend(['sin() function','Taylor Series - 3 terms'])
# Cos 함수
fig, g2 = plt.subplots()
g2.plot(angles,p_cos)
g2.plot(angles,t_cos)
g2.set_ylim([-5,5])
g2.legend(['cos() function','Taylor Series - 3 terms'])
plt.show()
[참고] ax.set_ylim([-5,5]) 를 함으로써 y의 범위를 축소시켜 관찰할 수 있는데, 이를 설정하지 않았을 경우
아래의 그림과 상당히 큰 y값 사이에서 진동하는 모습을 관찰 할 수가 없을 것이다.
Taylor Series - n Terms : Sin, Cos함수와 1 ~ 6 Terms 함수 비교
앞에서 만들어둔 func_cos( x, n ) 함수를 활용하여
1 ~ 5 차수까지의 Cos Taylor 함수를 그래프에 그려서 비교해보자.
import math
import numpy as np
import matplotlib.pyplot as plt
angles = np.arange( -2*np.pi, 2 * np.pi, 0.1)
p_cos = np.cos( angles )
p_sin = np.sin ( angles )
fig, g1 = plt.subplots()
g1.set_ylim([-7,3])
g1.plot(angles, p_sin)
fig, g2 = plt.subplots()
g2.set_ylim([-7,3])
g2.plot( angles,p_cos )
# 1차수부터 5차수 까지의 Sin Taylor Series
for n in range ( 1, 6 ) :
t_sin = [func_sin(angle, n) for angle in angles]
g1.plot(angles, t_sin)
# 1차수부터 5차수 까지의 Cos Taylor Series
for n in range( 1, 6 ):
t_cos = [func_cos( angle, n ) for angle in angles]
g2.plot( angles,t_cos )
plt.show()
[참고] 관찰하기 편하도록 set_ylim([ -7, 3 ])로 지정해 주었습니다.
작업한 Colab 주소
Google Colaboratory Notebook
Run, share, and edit Python notebooks
colab.research.google.com
728x90
'CS_컴퓨터이론 > 수치해석' 카테고리의 다른 글
[수치해석 / Colab ] Bisection , FalsePosition 슈도코드 프로그래밍 (0) | 2022.11.22 |
---|---|
[수치해석 / Colab] 테일러 급수로 자연로그함수 구하기 (0) | 2022.11.20 |
[수치해석] Open Method : Simple Fixed-Point Iteration & The Newton-Raphson Method (0) | 2022.10.23 |
[수치해석] The False-Position Method (0) | 2022.10.23 |
[수치해석] 초월함수에서 근을 찾는 방법, Bisection (Roots of Equation :: Bracketing of Bisection Methods) (0) | 2022.10.23 |