Use loops to write a program that computes the value of by using the following formula.
e ^ x = 1+x/1!+x^2/2!+x^3/3!+ ...
Notice that do not import factorial function in math module.
Sample answers:e=2.71828 and e^2=7.389056
Use loops to write a program that computes the value of by using the following formula.
e ^ x = 1+x/1!+x^2/2!+x^3/3!+ ...
Notice that do not import factorial function in math module.
Sample answers:e=2.71828 and e^2=7.389056
Without using factorial:
def calc_exp(x, n = 10):
' calc e^x using 1+x/1!+x^2/2!+x^3/3!+ . with a default of 10 terms (n = 10) '
term = 1 # First term is 1
result = term # init result to first term of series
for k in range(1, n):
term *= x/k # current term is (previous term)*x/k (i.e. effectively x^k/k!)
result += term # add current term
return result
Test
for x in [1, 2]:
print(f'e^{x} = {calc_exp(x)}') # Use print('e^{} = {}'.format(x, calc_exp(x)))
# for earlier than Python 3.6
Output
e^1 = 2.7182815255731922
e^2 = 7.3887125220458545
You can use the accumulate() function (from itertools) to build the series with your specified number of terms, then use the sum() function to add them all up:
from itertools import accumulate
def exp(x,terms=20):
return sum(accumulate(range(1,terms+1),lambda t,i:t*x/(i-1)))
print(exp(1)) # 2.7182818284590455
print(exp(2)) # 7.389056098925863
It can also be done recursively (without libraries):
def exp(x,terms=20,f=1):
return 1 + x/f if f==terms else 1 + x*exp(x,terms,f+1)/f
The way the recursive function works is by building the series progressively going backward from the last term. This approach converges faster than adding terms (probably because it doesn't lose as much precision on each iteration)
from depest recursion level up to initial function call:
f=20: 1 + x/f F20: 1 + x/20
f=19: 1 + x * F20 / f F19: 1 + x * (1 + x/20) / 19
1 + x/19 + x^2/(20*19)
f=18: 1 + x * F19 / f F18: 1 + x * (1 + x/19 + x^2/(20*19)) / 18
1 + x/18 + x^2/(19*18) + x^3/(20*19*18)
f=17: 1 + x * F18 / f F17: 1 + x/17 + x^2/(18*17) + x^3/(19*18*17) + ...
...
f=3 : 1 + x * F4 / f F3: 1 + x/3 + x^2/(4*3) + x^3/(5*4*3) + ...
f=2 : 1 + x * F3 / f F2: 1 + x/2 + x^2/(3*2) + x^3/(4*3*2) + ...
f=1 : 1 + x * F2 / f exp: 1 + x/1 + x^2/(2*1) + x^3/(3*2*1) + ...
Or, if you don't like recursion, an iterative solution is also possible:
def exp(x,terms=20):
result = 1
for f in range(terms,0,-1):
result = 1 + x * result / f
return result
Note that in all cases, as x gets larger, you will need more terms to get the desired precision