Reputation: 10946
In a project using SciPy and NumPy, when should one use scipy.pi
vs numpy.pi
vs just math.pi
? Is there a difference between these values?
Upvotes: 177
Views: 242901
Reputation: 23331
If we look at its source code, scipy.pi
(scipy.constants.pi
for scipy>=1.12)1 is precisely math.pi
; in fact, it's defined as
import math as _math
pi = _math.pi
You can verify that scipy.constants.pi is math.pi
returns True.
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 no dependency issues when importing it. For example, for pi
in Tensorflow code in Python, one could use tf.constant(math.pi)
.
1 Since scipy 1.12, scipy.pi
shortcut has been removed and all constants are accessible via the constants
sub-module.
Upvotes: 8
Reputation: 251548
>>> 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.
Upvotes: 255
Reputation: 789
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
Upvotes: 52