Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find ex in an efficient way in Python
The mathematical constant e raised to the power x (ex) can be calculated efficiently using the Taylor series expansion without library functions. The formula for ex is:
ex = 1 + x + x²/2! + x³/3! + x?/4! + ...
For example, if x = 5, then e5 ? 148.4131 because e5 = 1 + 5 + (5²/2!) + (5³/3!) + ... = 148.4131...
Algorithm
To solve this efficiently, we follow these steps ?
- Initialize factorial = 1, result = 1, and numerator = x
- Set n = 20 (number of terms for precision)
- For each term from 1 to n:
- Add (numerator/factorial) to result
- Update numerator = numerator × x
- Update factorial = factorial × (i+1)
- Return the calculated result
Implementation
def calculate_exp(x):
factorial = 1
result = 1
n = 20 # Number of terms for precision
numerator = x
for i in range(1, n):
result += numerator / factorial
numerator = numerator * x
factorial = factorial * (i + 1)
return result
# Test the function
x = 5
exp_value = calculate_exp(x)
print(f"e^{x} = {exp_value:.4f}")
# Compare with different values
test_values = [1, 2, 3, 5]
for val in test_values:
result = calculate_exp(val)
print(f"e^{val} = {result:.4f}")
e^5 = 148.4132 e^1 = 2.7183 e^2 = 7.3891 e^3 = 20.0855 e^5 = 148.4132
How It Works
The algorithm builds each term of the Taylor series incrementally. Instead of recalculating xi and i! from scratch for each term, it updates the numerator and factorial efficiently ?
- Term 1: numerator = x, factorial = 1
- Term 2: numerator = x², factorial = 2
- Term 3: numerator = x³, factorial = 6
- And so on...
Precision Control
def calculate_exp_precision(x, terms=20):
factorial = 1
result = 1
numerator = x
for i in range(1, terms):
result += numerator / factorial
numerator = numerator * x
factorial = factorial * (i + 1)
return result
# Test with different precision levels
x = 2
for terms in [10, 15, 20, 25]:
result = calculate_exp_precision(x, terms)
print(f"e^{x} with {terms} terms = {result:.6f}")
e^2 with 10 terms = 7.389056 e^2 with 15 terms = 7.389056 e^2 with 20 terms = 7.389056 e^2 with 25 terms = 7.389056
Conclusion
The Taylor series method efficiently calculates ex by incrementally building terms instead of recalculating powers and factorials. Using 20 terms provides sufficient precision for most applications, with a time complexity of O(n).
---