Fall, 2020
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\).
An example solution: sphere_sol
If you want to be more exact, you can import the NumPy module which includes a more precise representation of \(\pi\):
1]: import numpy as np
In [
2]: print(np.pi)
In [3.141592653589793
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
.
1]: import math
In [
2]: import numpy
In [
3]: import scipy
In [
4]: print(math.pi)
In [3.141592653589793
5]: print(numpy.pi)
In [3.141592653589793
6]: print(scipy.pi)
In [3.141592653589793
7]: print(math.pi == scipy.pi)
In [True
8]: print(math.pi == numpy.pi)
In [True
9]: print(scipy.pi == numpy.pi)
In [True
The constants represented in SciPy are list here: SciPy Constants. Constants in the Python math
module are listed here: math constants.