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?
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