Efficient program to calculate e^x in Python
In this tutorial, we learn how to calculate the exponential value in Python, and also we will learn how to write an efficient program for calculating exponential value. Now let us learn, what is an exponential function?
In mathematics, exponential is a function of the form f(x) = e^x.It is defined as a power series as shown below:
f(x) = e^x = 1+x+(x^2/2!)+(x^3/3!)+………….+(x^n/n!) ——————— (1)
It is difficult to find up to n Terms. So, we will find the sum of the first 100 terms(There is no difference in result). Then, eq.(1) can be written as:
f(x) = e^x ≈ 1+x+(x^2/2!)+(x^3/3!)+………….+(x^100/100!)
Now, do the above problem in your own editor and then look at the below code:
calculate e^x in Python
def fact(i): if i==1: return 1 else: return i*fact(i-1) x = int(input("Enter a number: ")) sum=1 for i in range(1,101): sum= sum+pow(x,i)/fact(i) print("The exponential value of {} is {}",.format(x,sum))
Explanation:
Step:1 Take input from the user using input() function and input is of integer type. Assign the input value to a variable :
x = int(input("Enter a number: ")
Step:2 In our problem, the first term is 1. Assign 1 to sum(sum is our final output):
sum = 1
Step:3 Now add all terms up to 100. In python we will add all terms for a loop as shown below:
for i in range(1,101): sum = sum + pow(x,i)/fact(i)
Here range(1,101) iterates loop 100 times. It starts form 1 to 100 and stops at 101. In each iteration the value is assigned to i. Python offers function pow(base,exponent) to calculate power of number. In this case, pow(base,exponent) function is used calculate x to the power of i.fact(i) computes the factorial of a number.
def fact(i): if i==1: return 1 else: return i*fact(i-1)
Step:4 Print the output on the console window:
print("The exponential value of {} is {}".format(x,sum))
Efficient Code:
If you are done with the above program. Very good…. if not, don’t worry. python allows you to calculate e^x using a function called exp(). Before using exp() function math library must be imported for this function to execute.
import math x = int(input("Enter a number: ") print(math.exp(x))
Also read: Numpy Exponential Function in Python
Leave a Reply