import numpy as np
print(np.pi)
3.141592653589793
The volume \(v\) of a sphere with radius \(r\) is given by:
\[\begin{equation} v = \frac{4}{3} \pi r^{3} \end{equation}\]
Write a short program to calculate the volume of a sphere with radius \(5\). You can approximate the value of \(\pi\) as \(3.14\).
Your program should output the following:
The volume of a sphere with radius 5 is 523.599
If you want to be more precise, you can import the NumPy module which includes a more precise representation of \(\pi\):
NumPy also includes a number of other built-in constants, you can see them here: NumPy Constants.
The Python modules called math
and scipy
also contain representations of the constant \(\pi\). Their representations of \(\pi\) are both equal to the one in numpy
.
In [1]: import math
In [2]: import numpy
In [3]: import scipy
In [4]: print(math.pi)
3.141592653589793
In [5]: print(numpy.pi)
3.141592653589793
In [6]: print(scipy.pi)
3.141592653589793
In [7]: print(math.pi == scipy.pi)
True
In [8]: print(math.pi == numpy.pi)
True
In [9]: print(scipy.pi == numpy.pi)
True
3.141592653589793
3.141592653589793
3.141592653589793
True
True
True
True
The constants represented in SciPy are list here: SciPy Constants. Constants in the Python math
module are listed here: math constants.