In a project using SciPy and NumPy, should I use scipy.pi
, numpy.pi
, or math.pi
?

- 10,268
- 18
- 50
- 51

- 10,510
- 8
- 31
- 58
-
4It's because you don't always use all of them, and you'd not want to install and import a module just to get Pi. – Lev Levitsky Sep 28 '12 at 18:40
-
17@LevLevitsky I just started using python and I noticed that there's a difference between math.exp and numpy.exp (numpy.exp can take a list but math.exp wants a float). So I didn't think it was a dumb question... – Douglas B. Staple Sep 28 '12 at 18:49
3 Answers
>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True
So it doesn't matter, they are all the same value.
The only reason all three modules provide a pi
value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.

- 242,874
- 37
- 412
- 384
-
20All other things being equal, I would use `math.pi` simply because it is in the standard library if the module doesn't depend on `numpy` or `scipy` otherwise -- But as you say, use pi in whichever module you're importing to begin with because they're all the same value. – mgilson Sep 28 '12 at 18:46
-
6If you're already using numpy use `np.pi`, but it doesn't make sense to import NumPy just for `pi` when it's in `math`. – asmeurer Aug 11 '16 at 18:40
One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:
import math
import numpy
import scipy
import sympy
print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False

- 749
- 1
- 6
- 7
-
9sympy Pi isn't stored as a constant/float, it's an object that contains the constant – Naib Jun 15 '15 at 08:53
-
27sympy's is exactly pi, represented symbolically, for doing symbolic math. the others are floating point approximations for doing floating point math. – endolith Feb 22 '16 at 16:41
-
3
If we look its source code, scipy.pi
is precisely math.pi
; in fact, it's defined as
import math as _math
pi = _math.pi
In their source codes, math.pi
is defined to be equal to 3.14159265358979323846
and numpy.pi
is defined to be equal to 3.141592653589793238462643383279502884
; both are well above the 15 digit accuracy of a float in Python, so it doesn't matter which one you use.
That said, if you're not already using numpy or scipy, importing them just for np.pi
or scipy.pi
would add unnecessary dependency while math
is a Python standard library, so there's not dependency issues. For example, for pi
in tensorflow code in python, one could use tf.constant(math.pi)
.

- 10,268
- 18
- 50
- 51