728x90

Evaluation of e^x using infinite Series

문제를 풀기에 앞서,

방법 1은 사용자가 Term를 지정해주는 방법, 테일러급수를 이용하여 접근을 하였다.

방법 2는 특정 조건까지 무한히 차수를 늘려가며 계산하는 방법이다.

 

import numpy as np
import math
import matplotlib.pyplot as plt

# 방법1
def func_e(x,n):
  approx_e = 0
  for i in range(n):
    num = x**i
    denom = math.factorial(i)
    term = num / denom
    approx_e += term
  print(approx_e, term)
  return approx_e
  
# 방법2 슈도코드를 기반으로 프로그래밍
# e^-10 을 구해보고자한다.
maxit = 1000000
es = 0.00000000001
x = -10

iter = 1
sol = 1
ea = 100
fac = 1
while True:
  solold = sol
  fac *= iter
  sol = sol + x**iter / fac
  iter += 1

  if sol !=  0 :
    ea = abs((sol - solold) / sol ) * 100
  print("iter=", iter, "  ea=", ea, "  es=", es, "  sol=", sol)

  if ea <= es or iter >= maxit :
    print("exact value = ", sol)
    break
728x90

+ Recent posts