The Python Oracle

Should I use scipy.pi, numpy.pi, or math.pi?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping

--

Chapters
00:00 Question
00:23 Accepted answer (Score 240)
00:52 Answer 2 (Score 49)
01:22 Answer 3 (Score 0)
02:50 Thank you

--

Full question
https://stackoverflow.com/questions/1264...

Answer 2 links:
[source code]: https://github.com/scipy/scipy/blob/main...
[defined]: https://github.com/python/cpython/blob/m...
[defined]: https://github.com/numpy/numpy/blob/main...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #numpy #scipy #pi

#avk47



ACCEPTED ANSWER

Score 254


>>> 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.




ANSWER 2

Score 52


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



ANSWER 3

Score 7


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).