Approximation of e^x using Maclaurin Series in Python

拈花ヽ惹草 提交于 2020-06-01 12:40:56

问题


I'm trying to approximate e^x using the Maclaurin series in a function called my_exp(x), I believe everything I've done so far is right but I'm getting incorrect approximations for whatever number I try.

import math
for i in range (x):
    exp = 1 + ((x**i)/math.factorial(i))
print(exp)

For example, whenever I try my_exp(12) I get 18614.926233766233 instead of 162754.79141900392 Help?


回答1:


Your problem is that the e^x series is an infinite series, and so it makes no sense to only sum the first x terms of the series.

def myexp(x):
  e=0
  for i in range(0,100): #Sum the first 100 terms of the series
    e=e+(x**i)/math.factorial(i)
  return e

You can also define the precision of your result and get a better solution.

def myexp(x):
    e=0
    pres=0.0001
    s=1
    i=1
    while s>pres:
        e=e+s
        s=(x**i)/math.factorial(i)
        i=i+1
    return e



回答2:


In order to accumulate the terms of the series, you need to replace the assignment to exp with a line such as:

exp = exp + ((x**i)/math.factorial(i))


来源:https://stackoverflow.com/questions/24915194/approximation-of-ex-using-maclaurin-series-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!