Suppose we have a number n. We have to find $e^{x}$ efficiently, without using library functions. The formula for $e^{x}$ is like
$$e^{x} = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + ...$$
So, if the input is like x = 5, then the output will be 148.4131 because e^x = 1 + 5 + (5^2/2!) + (5^3/3!) + ... = 148.4131...
To solve this, we will follow these steps −
- fact := 1
- res := 1
- n := 20 it can be large for precise results
- nume := x
- for i in range 1 to n, do
- res := res + nume/fact
- nume := nume * x
- fact := fact *(i+1)
- return res
Example
Let us see the following implementation to get better understanding −
def solve(x): fact = 1 res = 1 n = 20 nume = x for i in range(1,n): res += nume/fact nume = nume * x fact = fact * (i+1) return res x = 5 print(solve(x))
Input
5
Output
143