Ref Math E
## Python math.e Constant
The **`math.e`** constant is a built-in property of the Python `math` module. It returns Euler's number ($e$), which is a mathematical constant approximately equal to $2.71828$.
Euler's number is an irrational number that serves as the base of natural logarithms and is widely used in calculus, compound interest calculations, physics, and machine learning algorithms (such as the sigmoid activation function).
---
### Syntax
To use the `math.e` constant, you must first import the `math` module:
```python
import math
math.e
```
### Return Value
* **Type:** `float`
* **Value:** `2.718281828459045` (represented to 15 decimal places of precision).
---
### Code Examples
#### 1. Basic Usage
The following example demonstrates how to import the `math` module and print the value of `math.e`.
```python
# Import the math module
import math
# Print the value of Euler's number (e)
print("The value of math.e is:", math.e)
```
**Output:**
```text
The value of math.e is: 2.718281828459045
```
#### 2. Practical Application: Calculating Compound Interest
Euler's number is fundamental to calculating continuously compounded interest using the formula:
$$A = P \cdot e^{rt}$$
Where:
* $P$ = Principal amount
* $r$ = Annual interest rate (as a decimal)
* $t$ = Time in years
```python
import math
principal = 1000 # $1000 initial investment
rate = 0.05 # 5% annual interest rate
years = 3 # Compounded continuously for 3 years
# Calculate continuous compound interest using math.e
amount = principal * (math.e ** (rate * years))
print(f"Future value after {years} years: ${amount:.2f}")
```
**Output:**
```text
Future value after 3 years: $1161.83
```
---
### Considerations & Best Practices
1. **Precision:** `math.e` is a double-precision float. While highly accurate for most engineering and scientific applications, floating-point arithmetic in computers has inherent precision limits.
2. **Alternative for Exponential Functions:** If you need to calculate $e^x$ (Euler's number raised to the power of $x$), it is highly recommended to use **`math.exp(x)`** instead of `math.e ** x`. `math.exp(x)` is more accurate and optimized for performance.
```python
import math
# Recommended approach for e^x
result_exp = math.exp(3)
# Alternative approach
result_power = math.e ** 3
print(result_exp) # 20.085536923187668
print(result_power) # 20.085536923187664 (Note the slight precision difference)
```
YouTip