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

Question:

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

Asked By: Douglas B. Staple

||

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.

Answered By: BrenBarn

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
Answered By: jbay

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

Answered By: cottontail
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.