🛠️ToolsShed

Euler's Number Calculator

Explore Euler's number e with Taylor series approximation, continuous compounding, and normal distribution.

Euler's Number (e)

e = 2.718281828459045

常见问题

代码实现

import math
from decimal import Decimal, getcontext

# 1. Taylor series approximation of e
def euler_taylor(n_terms: int) -> float:
    """Approximate e using n terms of Taylor series: sum(1/k!) for k=0..n"""
    total = 0.0
    factorial = 1
    for k in range(n_terms):
        if k > 0:
            factorial *= k
        total += 1 / factorial
    return total

# 2. High-precision e using Python's decimal module
def euler_high_precision(decimal_places: int) -> Decimal:
    getcontext().prec = decimal_places + 10  # extra guard digits
    e = Decimal(0)
    factorial = Decimal(1)
    for k in range(200):  # 200 terms is enough for 100+ decimal places
        if k > 0:
            factorial *= k
        term = Decimal(1) / factorial
        e += term
        if term < Decimal(10) ** -(decimal_places + 5):
            break
    return +e  # re-apply precision

# 3. Common formulas involving e
def compound_continuous(principal: float, rate: float, years: float) -> float:
    """A = P × e^(r×t) — continuous compounding formula"""
    return principal * math.exp(rate * years)

def normal_pdf(x: float, mu: float = 0, sigma: float = 1) -> float:
    """Normal distribution PDF: f(x) = (1/σ√2π) × e^(-(x-µ)²/2σ²)"""
    return (1 / (sigma * math.sqrt(2 * math.pi))) * math.exp(-((x - mu)**2) / (2 * sigma**2))

# Examples
print(f"e (Python math):     {math.e}")
print(f"e (5 terms):         {euler_taylor(5):.8f}")
print(f"e (20 terms):        {euler_taylor(20):.15f}")

# Euler's identity: e^(iπ) + 1 = 0
e_to_ipi = math.exp(complex(0, math.pi))
print(f"\ne^(iπ) = {e_to_ipi.real:.10f} + {e_to_ipi.imag:.0f}i")
print(f"e^(iπ) + 1 = {e_to_ipi.real + 1:.2e}  (≈ 0, Euler's identity)")

# Continuous compounding
amount = compound_continuous(1000, 0.05, 10)
print(f"\n$1000 at 5% for 10 years (continuous): ${amount:.2f}")

# Normal distribution at x=0
print(f"Normal PDF at x=0: {normal_pdf(0):.6f}")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.