Marquette University, view of Wisconsin Avenue  

Module 17

The Random Module

Simulation is a common scientific tool and this module treats the way to generate random numbers and similar things with Python 3 with the random module. To show this module in action, we look at the Monte Carlo method for approximating volumes, areas, and integrals.

A complicated volume in 3D

The image above shows a volume defined by the equation for a torus and intersected with two hyperplanes, e.g. a donut that has been cut twice and all but one piece removed. An exact calculation of this volume is very challenging and certainly exceeds the skills given in the Calculus sequence. However, Monte Carlo gives a rather simple, if not completely accurate solution.

The idea of Monte Carlo is to produce a large number of points distributed uniformly within the enclosing cube [-1.5, 1.5] × [-1.5, 1.5] × [-1.5, 1.5] . We then count the number of points within the volume. The ratio of the number of points within over the total number of points generated is then approximately equal to the ratio of the volume over the volume of the cube. The latter is 3 × 3 × 3 as the length of the sides of the cubes are 3.

To generate points randomly, we use the method random.uniform to randomly select three coordinates of the random point inside the cube. This gives us the following code.


import random
import math

N = int(input("Give the number of random points: "))
count = 0
for _ in range(N):
    x = random.uniform(-1.5,1.5)
    y = random.uniform(-1.5,1.5)
    z = random.uniform(-1.5,1.5)
    if (1-math.sqrt(x**2+y**2))**2+z**4<0.2 and x-y<0.9 and x+z<0.1 and x+y<1.8:
        count += 1
print("The area is approximately", count*27/N)

The if-statement checks whether the point with coordinates (x,y,z) is inside the volume or not. If it is, it increments the count. Finally, the volume is approximately the number of points inside over the total number of points, multiplied by the volume of the block.