Pi in Python
Quick Summary
Use the math.pi
constant
import math
print(math.pi)
3.141592653589793
math
is a module from the Python Standard Library, which means that you'll have it available with any Python version, without installing any additional packages.
numpy.pi constant
If you're already using Numpy, it conveniently provides π as a constant.
import numpy as np
print(np.pi)
scipy.py constant
Similar to numpy
, scipy
also comes with a predefined pi
constant
import scipy
print(scipy.pi)
Are they all the same?
If you're wondering which constant to use, they are all the same value. You can check this for yourself:
import math
import numpy
import scipy
print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
If you're not using the libraries for scientific and numerical computing, numpy
/ scipy
, your best bet is math.pi
from the standard library.
Otherwise, it just depends on the circumstance. Typically you'll want to minimize the number of module imports and be consistent with the rest of the codebase, so that may help you decide.