How to Use Pi in Python: math.pi, numpy.pi, scipy, and More
Updated on
Need pi (π) in Python? The fastest way is math.pi from the standard library — no install required. For NumPy array work, use np.pi. This guide covers every method, when to use each one, and practical examples you can copy straight into your code.
Quick Reference: Pi Constants in Python
| Method | Code | Value | Install Required? | Best For |
|---|---|---|---|---|
math.pi | import math; math.pi | 3.141592653589793 | No (stdlib) | General use, scripts |
numpy.pi | import numpy as np; np.pi | 3.141592653589793 | Yes (pip install numpy) | Array math, data science |
scipy.constants.pi | from scipy.constants import pi | 3.141592653589793 | Yes (pip install scipy) | Scientific computing |
sympy.pi | import sympy; sympy.pi | Exact symbolic π | Yes (pip install sympy) | Symbolic math, arbitrary precision |
mpmath.pi | import mpmath; mpmath.pi | Arbitrary precision | Yes (pip install mpmath) | 1000+ decimal places |
All float-based constants return the same IEEE 754 double-precision value: 3.141592653589793 (15 significant digits).
Using math.pi (Standard Library)
math.pi is the simplest way to use pi in Python. It's part of the standard library, so there's nothing to install.
import math
print(math.pi)
# 3.141592653589793You can also import just the constant:
from math import pi
print(pi)
# 3.141592653589793Practical Example: Circle Area and Circumference
from math import pi
radius = 5
area = pi * radius ** 2
circumference = 2 * pi * radius
print(f"Radius: {radius}")
print(f"Area: {area:.2f}") # 78.54
print(f"Circumference: {circumference:.2f}") # 31.42Trigonometry with math.pi
Python's math.sin(), math.cos(), and math.tan() take angles in radians, not degrees. Use math.pi to convert:
import math
# 90 degrees in radians
angle_rad = math.pi / 2
print(math.sin(angle_rad)) # 1.0
print(math.cos(angle_rad)) # ~0 (6.12e-17 due to floating point)
print(math.tan(math.pi / 4)) # ~1.0
# Convert degrees to radians
degrees = 45
radians = degrees * math.pi / 180 # or use math.radians(45)
print(math.sin(radians)) # 0.7071067811865476Using numpy.pi (NumPy)
If you're already using NumPy for numerical computation, np.pi is the convenient choice. The value is identical to math.pi.
import numpy as np
print(np.pi)
# 3.141592653589793Why Use numpy.pi Over math.pi?
numpy.pi shines when you're working with arrays. NumPy broadcasts pi across entire arrays without explicit loops:
import numpy as np
# Generate angles from 0 to 2π
angles = np.linspace(0, 2 * np.pi, 8, endpoint=False)
# Compute sine values for all angles at once
sine_values = np.sin(angles)
for angle, sine in zip(angles, sine_values):
print(f"sin({angle:.4f}) = {sine:.4f}")Vectorized Circle Calculations
import numpy as np
radii = np.array([1, 2, 3, 4, 5])
areas = np.pi * radii ** 2
circumferences = 2 * np.pi * radii
print("Radii:", radii)
print("Areas:", np.round(areas, 2))
print("Circumferences:", np.round(circumferences, 2))Using scipy.constants.pi
SciPy provides pi alongside other physical and mathematical constants. The value is the same float, but it's useful when your code already depends on scipy.constants for other values.
from scipy.constants import pi, e, golden
print(f"π = {pi}")
print(f"e = {e}")
print(f"φ = {golden}")math.pi vs numpy.pi vs scipy.constants.pi
import math
import numpy as np
from scipy.constants import pi as scipy_pi
print(math.pi == np.pi == scipy_pi) # TrueAll three return exactly the same float. Here's when to use each:
| Scenario | Recommended | Reason |
|---|---|---|
| Simple scripts, no dependencies | math.pi | Standard library, no install |
| NumPy array calculations | np.pi | Already imported, array-friendly |
| Scientific code using scipy | scipy.constants.pi | Consistent with other constants |
| Symbolic math / proofs | sympy.pi | Exact representation, not a float |
| Need 1000+ digits of pi | mpmath.pi | Arbitrary precision |
Getting Pi to Arbitrary Precision
The standard math.pi gives you 15 decimal places (IEEE 754 double). If you need more — for research, benchmarking, or educational purposes — use mpmath:
from mpmath import mp
# Set precision to 50 decimal places
mp.dps = 50
print(mp.pi)
# 3.1415926535897932384626433832795028841971693993751
# Set precision to 100 decimal places
mp.dps = 100
print(mp.pi)SymPy also supports arbitrary precision through evalf():
import sympy
# Get pi to 50 decimal places
print(sympy.pi.evalf(50))
# 3.1415926535897932384626433832795028841971693993751Calculating Pi with Python Algorithms
Beyond using built-in constants, you can compute pi programmatically. This is useful for learning, interviews, and understanding numerical methods.
Leibniz Series
The Leibniz formula: π/4 = 1 - 1/3 + 1/5 - 1/7 + ...
def leibniz_pi(n_terms: int) -> float:
"""Approximate pi using the Leibniz series."""
pi = 0.0
for i in range(n_terms):
pi += ((-1) ** i) / (2 * i + 1)
return 4 * pi
print(f" 1,000 terms: {leibniz_pi(1_000):.10f}")
print(f"100,000 terms: {leibniz_pi(100_000):.10f}")
print(f" Actual math.pi: {3.141592653589793:.10f}")The Leibniz series converges slowly — you need ~300,000 terms for 5 correct decimal places.
Monte Carlo Estimation
Throw random points at a square and count how many land inside the inscribed circle:
import random
def monte_carlo_pi(n_points: int) -> float:
"""Estimate pi using Monte Carlo simulation."""
inside = sum(
1 for _ in range(n_points)
if random.random() ** 2 + random.random() ** 2 <= 1
)
return 4 * inside / n_points
# More points = better estimate
for n in [1_000, 10_000, 100_000, 1_000_000]:
estimate = monte_carlo_pi(n)
error = abs(estimate - 3.141592653589793)
print(f"{n:>10,} points: π ≈ {estimate:.6f} (error: {error:.6f})")Chudnovsky Algorithm (Fast Convergence)
The Chudnovsky algorithm is what libraries like mpmath use internally. Each term adds ~14 digits:
from decimal import Decimal, getcontext
def chudnovsky_pi(precision: int) -> Decimal:
"""Calculate pi using the Chudnovsky algorithm."""
getcontext().prec = precision + 10
C = 426880 * Decimal(10005).sqrt()
K, M, X, L, S = 6, 1, 1, 13591409, 13591409
for i in range(1, precision):
M = M * (K ** 3 - 16 * K) // ((i) ** 3)
K += 12
L += 545140134
X *= -262537412640768000
S += Decimal(M * L) / X
return C / S
pi = chudnovsky_pi(50)
print(f"Chudnovsky: {pi}")Common Mistakes with Pi in Python
1. Degrees vs Radians
import math
# WRONG: passing degrees directly
print(math.sin(90)) # 0.8939... (not 1.0!)
# CORRECT: convert to radians first
print(math.sin(math.pi/2)) # 1.0
print(math.sin(math.radians(90))) # 1.02. Floating-Point Precision
import math
# This is NOT exactly zero due to floating-point arithmetic
result = math.cos(math.pi / 2)
print(result) # 6.123233995736766e-17
print(result == 0) # False
# Use math.isclose() for comparisons
print(math.isclose(result, 0, abs_tol=1e-9)) # True3. Defining Pi Manually
# DON'T: lose precision with manual constants
pi = 3.14
area = pi * 10 ** 2 # 314.0 (inaccurate)
# DO: use math.pi for full precision
import math
area = math.pi * 10 ** 2 # 314.1592653589793Practical Applications
Sphere Volume and Surface Area
import math
def sphere_volume(radius: float) -> float:
return (4/3) * math.pi * radius ** 3
def sphere_surface_area(radius: float) -> float:
return 4 * math.pi * radius ** 2
r = 7
print(f"Sphere (r={r}): volume = {sphere_volume(r):.2f}, surface area = {sphere_surface_area(r):.2f}")Polar to Cartesian Coordinate Conversion
import math
def polar_to_cartesian(r: float, theta_degrees: float) -> tuple:
"""Convert polar coordinates (r, θ°) to cartesian (x, y)."""
theta_rad = math.radians(theta_degrees)
x = r * math.cos(theta_rad)
y = r * math.sin(theta_rad)
return round(x, 6), round(y, 6)
# Example: point at distance 5, angle 60°
print(polar_to_cartesian(5, 60)) # (2.5, 4.330127)
print(polar_to_cartesian(10, 45)) # (7.071068, 7.071068)Pendulum Period
import math
def pendulum_period(length_m: float, g: float = 9.81) -> float:
"""Calculate the period of a simple pendulum in seconds."""
return 2 * math.pi * math.sqrt(length_m / g)
print(f"1m pendulum: {pendulum_period(1):.3f} seconds") # ~2.006sVisualizing Pi with Python
If you're working with data science tools, you can visualize pi-related functions easily:
import numpy as np
# Generate sine wave data
x = np.linspace(0, 4 * np.pi, 200)
y_sin = np.sin(x)
y_cos = np.cos(x)Tip: Turn your NumPy data into interactive visualizations instantly with PyGWalker (opens in a new tab). Import your DataFrame, and PyGWalker gives you a drag-and-drop Tableau-like interface right inside Jupyter Notebook — no extra code needed.
FAQs
How do I get pi in Python without importing anything?
You can approximate pi without imports, but it's not recommended for production code:
pi_approx = 355 / 113 # 3.1415929... (accurate to 6 decimal places)
# Or use: 22/7 = 3.142857... (only 2 decimal places)Always prefer math.pi for accurate calculations.
Is math.pi the same as numpy.pi?
Yes. Both return the identical IEEE 754 double-precision float: 3.141592653589793. Use math.pi if you don't need NumPy; use np.pi if you're already working with NumPy arrays.
How many digits of pi does Python store?
The standard math.pi stores 15 significant decimal digits (IEEE 754 double-precision). For more digits, use mpmath:
from mpmath import mp
mp.dps = 1000 # 1000 decimal places
print(mp.pi)How do I convert degrees to radians in Python?
Use math.radians() or multiply by math.pi / 180:
import math
radians = math.radians(90) # 1.5707963267948966
radians = 90 * math.pi / 180 # same resultCan I use pi in Python without importing math?
Yes — use numpy.pi, scipy.constants.pi, or sympy.pi. But if you want zero dependencies, math.pi is your best option since math is in the standard library and requires no installation.