davkav9
davkav9

Reputation: 137

Approximation of e^x using Maclaurin Series in Python

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?

Upvotes: 0

Views: 20619

Answers (2)

Sergio Peñafiel
Sergio Peñafiel

Reputation: 476

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

Upvotes: 2

Pascal Cuoq
Pascal Cuoq

Reputation: 80355

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

Upvotes: 2

Related Questions