Using Pi in Python
A very trivial scenario that you will come across in coding is using the value of Pi in Python language. And as it turns out, there are multiple libraries Numpy (np.pi) , Scipy (scipy.pi), and Math (math.pi) with which you can use the value of Pi in Python. Let us see them one by one.
i) Pi in Numpy â€“ np.pi
Here we import the Numpy library as np. And the value of pi can be accessed by using np.pi as shown in the example below.
In [0]:
importÂ numpyÂ asÂ np print('ValueÂ ofÂ PiÂ usingÂ np.piÂ is',Â np.pi);
Out[0]:
Value of Pi using np.pi is 3.141592653589793
Â
ii) Pi in Scipy â€“ scipy.pi
Here the Scipy library is imported and then the value of pi is accessed by using scipy.pi as shown below.
In [1]:
importÂ scipy print('ValueÂ ofÂ PiÂ usingÂ scipy.piÂ is',Â scipy.pi);
Out[1]:
Value of Pi using scipy.pi is 3.141592653589793
Â
iii) Pi in Math â€“ math.pi
Finally, we can use the math library of python to use the value of pi with math.pi as explained in the below example.
In [2]:
import math print('ValueÂ ofÂ PiÂ usingÂ math.piÂ is',Â math.pi);
Out[2]:
Value of Pi using math.pi is 3.141592653589793
Â
np.pi vs scipy.pi vs math.pi
We saw three ways of using pi in Python. So let us first confirm if the value of pi returned by them are all same.
In the below snippet we are comparing the value of all three and the output confirms that the value of Pi is the same for them.
In[3]:
ifÂ np.piÂ ==Â scipy.piÂ ==Â math.pi: Â print('ValuesÂ ofÂ PiÂ same') else: Â print('ValuesÂ ofÂ PiÂ isÂ NOTÂ same')
Out[3]:
Values of Pi same
Â
So now the question arises which of the three options we should use in Python if the value of Pi is the same in each of the three. Well, it does not really matter, you can use any option, but it is ideal to use the pi from the library if you are already using it in your code. E.g. if you are already working with the numpy code then it will make more sense to use np.pi instead of the other two options.
Conclusion
Hope you liked our quick tutorial on using the value of Pi in Python with Numpy, Scipy, and Math libraries. You can use any of the three approaches, it is just a matter of convenience.

MLK is a knowledge sharing community platform for machine learning enthusiasts, beginners and experts. Let us create a powerful hub together to Make AI Simple for everyone.