py4u blog

Mathematical Constants in Python: A Comprehensive Guide

Mathematical constants like π, e, and τ are fundamental to scientific computing, physics, and engineering. Python provides easy access to these constants through built-in libraries like math and specialized packages. This blog explores Python's mathematical constants, their precision, best practices for usage, and real-world applications. Whether you're calculating circle areas or modeling exponential growth, understanding these constants will streamline your numerical workflows.


2026-07

Table of Contents#

  1. The math Module: Core Constants
    • π (pi)
    • e (Euler's Number)
    • τ (tau)
    • inf (Infinity)
    • nan (Not a Number)
  2. Constants in Specialized Libraries
    • NumPy's Constants
    • SciPy's Special Constants
  3. Best Practices & Common Pitfalls
  4. Practical Examples
    • Geometry Calculations
    • Exponential Models
    • Infinite Series
  5. Conclusion
  6. References

1. The math Module: Core Constants#

Python’s standard library includes the math module, which provides key constants with precision up to 15–17 decimal places (IEEE 754 double-precision).

π (pi)#

Definition: Ratio of a circle's circumference to its diameter (~3.14159).
Access: math.pi
Common Use: Geometry, trigonometry, Fourier transforms.

import math
 
# Calculate area of a circle
radius = 5
area = math.pi * radius ** 2
print(area)  # Output: 78.53981633974483

e (Euler's Number)#

Definition: Base of natural logarithms (~2.71828).
Access: math.e
Common Use: Exponential growth, compound interest, probability.

# Continuous compounding interest
principal = 1000
rate = 0.05
time = 10
amount = principal * math.e ** (rate * time)
print(amount)  # Output: 1648.7212707001282

τ (tau)#

Definition: Circle constant equal to 2π (~6.28318).
Access: math.tau
Common Use: Angular calculations (radians), simplifying periodic functions.

# Convert degrees to radians (using τ for a full circle)
degrees = 180
radians = degrees * (math.tau / 360)
print(radians)  # Output: 3.141592653589793

inf (Infinity)#

Definition: Positive/negative infinity.
Access: math.inf or -math.inf
Common Use: Comparisons, algorithm bounds, overflow handling.

# Check if a number exceeds system limits
x = 1e308
if x > math.inf:
    print("Overflow!")
else:
    print(math.isinf(x))  # Output: False (since 1e308 < inf)

nan (Not a Number)#

Definition: Undefined or unrepresentable values.
Access: math.nan
Common Use: Placeholder for missing data, error handling.

# Handle invalid operations
result = 0 / 0  # Raises error; better to use:
result = math.nan
print(math.isnan(result))  # Output: True

2. Constants in Specialized Libraries#

NumPy Constants#

NumPy provides high-precision versions and physical constants.
Example: numpy.pi (same as math.pi but vectorized).

import numpy as np
 
# Array operations with π
angles = np.array([0, np.pi/2, np.pi])
sines = np.sin(angles)  # [0., 1., 0.]

SciPy's Special Constants#

SciPy’s scipy.constants includes physical constants (e.g., speed of light, Planck’s constant).

from scipy import constants
 
# Speed of light in m/s
c = constants.c  # 299792458.0
 
# Planck's constant
h = constants.h  # 6.62607015e-34

3. Best Practices & Common Pitfalls#

  1. Precision Awareness:

    • math constants are precise to ~15–17 digits. Use decimal.Decimal for higher precision.
    from decimal import Decimal, getcontext
    getcontext().prec = 50  # 50-digit precision
    pi_high_precision = Decimal('3.14159265358979323846264338327950288419716939937510')
  2. Equality Checks with nan/inf:

    • Use math.isnan()/math.isinf() instead of ==.
    # Wrong: 
    if x == math.nan:  # Always False
    # Correct:
    if math.isnan(x):
  3. Library-Specific Behavior:

    • NumPy’s np.nan behaves identically to math.nan but supports array operations.
  4. Performance:

    • Prefer math over NumPy for scalar operations (faster execution).

4. Practical Examples#

Calculating Circle Segment Area#

def circle_segment_area(radius, angle_degrees):
    angle_radians = math.radians(angle_degrees)
    return 0.5 * radius ** 2 * (angle_radians - math.sin(angle_radians))
 
print(circle_segment_area(10, 90))  # Output: ~28.539816

Modeling Radioactive Decay#

half_life = 5730  # Carbon-14 half-life (years)
decay_constant = math.log(2) / half_life  # Using ln(2)
remaining_fraction = math.e ** (-decay_constant * 1000)
print(f"Remaining after 1000 years: {remaining_fraction:.1%}")

Infinite Series Convergence#

# Sum of 1/n^2 converges to π²/6
target = math.pi ** 2 / 6
sum_val = 0.0
n = 1
while abs(target - sum_val) > 1e-10:
    sum_val += 1 / (n ** 2)
    n += 1
print(sum_val)  # Output: ~1.64493

5. Conclusion#

Python’s math module provides accessible, precise implementations of key mathematical constants. By leveraging math.pi, math.e, math.tau, and handling edge cases with math.inf/math.nan, you can write cleaner and more reliable numerical code. For specialized needs, libraries like NumPy and SciPy extend these capabilities with physical constants and vectorized operations. Always match the constant’s source (math, NumPy, etc.) to your use case for optimal performance and correctness.


References#

  1. Python math Module Documentation: https://docs.python.org/3/library/math.html
  2. NumPy Constants: https://numpy.org/doc/stable/reference/constants.html
  3. SciPy Constants: https://docs.scipy.org/doc/scipy/reference/constants.html
  4. IEEE 754 Standard (Floating-Point Arithmetic): https://ieeexplore.ieee.org/document/4610935
  5. Tau Manifesto: https://tauday.com/tau-manifesto