问题
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