home

Scientific Computing (Psychology 9040a)

Fall, 2020

Radius of a sphere


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


Going Beyond

some more information about mathematical constants

If you want to be more exact, you can import the NumPy module which includes a more precise representation of \(\pi\):

In [1]: import numpy as np                                                      

In [2]: print(np.pi)                                                            
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.

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

The constants represented in SciPy are list here: SciPy Constants. Constants in the Python math module are listed here: math constants.