PHYSICS 2235

### PHYSICS 2235 Lab 09

In this lab, we explore the use of random numbers in programming using numpy.random . Random numbers are useful in modeling stochastic processes as simple as flipping a coin or rolling dice, or as advanced as quantum mechanical probabilities. Random numbers can be used to generate simulated data sets with uncertainties. They are also commonly utilized to perform integration in what is known as the Monte Carlo technique.

#### Exercise 1: Uniformly distributed random numbers

Numpy provides several random number generators. In this example we focus on rand which return a random number from 0-1.
#! /usr/local/bin/python3

import numpy as np

x1 = np.random.rand()

x2 = np.random.rand(5)

a, b = 1, 20
x3 = (b-a)*np.random.rand(20) + a


explaining code

• look at the content of x1,x2,x3. What do they return?
• Use rand to return 50 random numbers between 10 and 30.

#### Exercise 2: Random distribution of integers.

In this example we focus on randint which returns a random integer number.

#! /usr/local/bin/python3

import numpy as np

x1 = np.random.randint(1,100,10)


explaining code

• Use randint to return the results of a series of "coin tosses". If randint returns 0 than the coin toss is head and if randint returns 1 than the coin toss is one.

#### Exercise 3: Normally distributed random numbers

It is often useful to generate random numbers according to distributions which are not "flat". The randn(N) utility will generate N random numbers following a Gaussian (also known as Normal) distribution with a mean (mu) of zero and a width (sigma) of 1.
import numpy as np
import matplotlib.pyplot as plt

plt.subplot(3,1,1)
x1 = np.random.randn(1000)
n2,b2,p2 = plt.hist(x1,bins=10,range=(-5.0,5.0),histtype='step',color='black')

plt.subplot(3,1,2)
mu , sigma = 5,10
x2= sigma* np.random.randn(1000) + mu
n3,b3,p3 = plt.hist(x2,bins=10,range=(-30.0,30.0),histtype='step',color='black')

plt.subplot(3,1,3)
n4,b4,p4 =plt.hist(x2,bins=100,range=(-30.0,30.0),histtype='step',color='black')

plt.show()


explaining code

Try changing the mean and width to see if the effect on the histogram is what you'd expect.
• First keep (sigma=1) and only change the mean. Change the mean to several values mu= 10, 20,50,500. What happens to the distribution. Note that you need to adjust the range every time you use a new mean. Adjust or even remove the range argument.
• Now keep the mean constant (mu=5) and change the sigma values (sigma=1,2,3,5,10). What happens to the distribution. You would also need to adjust or remove the range argument.
• Is the effect of changing the mean and the sigma what you expect?
• Add some print statements and see if you can figure out what are the values of n2,b2 .

#### Exercise 4: probability distribution

In addition to plotting the histogram " count vs. variable" you can also plot the probability histogram " probability of count vs. variable." This is also done by matplotlib function hist Keyword arguments weights as shown below.
#! /usr/local/bin/python3

import numpy as np
import matplotlib.pyplot as plt

a, b = 0, 10
x1 = (b-a)*np.random.rand(100) + a

weights1 = np.ones_like(x1)
weights2 = np.ones_like(x1)/float(len(x1))

plt.subplot(2,1,1)
n1, b1, p1= plt.hist(x1,bins=10,range=(0.0,10.0),histtype='stepfilled',color='green', weights=weights1,alpha=0.5)
plt.title('Count distribution')
plt.ylabel('Counts')
plt.xlabel('x')

plt.subplot(2,1,2)
n2,b2,p2 = plt.hist(x1,bins=10,range=(0.0,10.0),histtype='stepfilled',color='blue',weights=weights2,alpha=0.5)
plt.title('Probability distribution')
plt.ylabel('P(x)')
plt.xlabel('x')

plt.tight_layout()
plt.show()

explaining code
find the sum of the bin values for the probability distribution. What should it equal to. Note that for an array b the sum of its elements can be achieved by using sum(b).

#### Problem 1

• part-a: Write a function dice2 that generate two random numbers and use these to assign each die a number between one and six with equal probability. The input of the function dice2 should be N the number of times it will generate two random numbers. Of course your histogram should allow integer entries between (at least) 2 and 12. "Roll" 2 dice N time where N = 10,000 times keeping track of all the sums of each set of rolls in a list. Then sum these two numbers and histogram the results. save histogram in dice2.png
• plot the probability distribution for part-a's histogram with title dice2prob.png
• part-b: Write a function dice3 using 3 dice and plot the resulting histogram.
• plot the probability distribution for the part-b's histogram with title dice3prob.png
• submit your python script myuserand.py and your plots dice2.png dice3.png dice2prob.png dice3prob.png . Add a title to each plot. Use histogram type stepfilled. With a color other than black.

#### Problem 2

For this problem, we will use the Monte Carlo integration technique to compute the value of π

Start with the code
pi.py , which generates two random numbers and generates a scatter plot of the results. Run the code as is and see the output.

Your task is to determine ( nhit )The number of points inside the blue circle of radius r=0.5 on the scatter plot. From that determine π. Submit your modified code mypi.py

pi.py also contains a function binomialError which will take the value of nhit and returns two values:
• The fraction f of the number of points hitting the circle to the total number of thrown points
• The uncertainty in the value of f
should print to the terminal your answer for the value of π and the expected uncertainty in π.

Hints:
• Note that the origin (0,0) is not at the center of the circle. This hint is important when selecting events inside or outside your object (the circle)
• From lecture
area \ of \ object = area \ of \ rectangle \times \frac{number \ of \ points \ inside \ the \ object}{total \ thrown \ number \ of \ points \ inside\ rectangle}

• what is the value of the
\frac{ area \ of \ object} { area \ of \ rectangle}
. How does it relate to the value of π knowing the radius of the circle and the area of your square.

#### Problem 3 (BONUS)

Use the function hist along with NumPy functions random.rand and random.randn to create the histogram graphs as shown in Fig. Histograms

Add the title Histograms of random numbers. Note: that your are plotting the (random and gaussian) probability distributions of x. submit hists.py and hists.png

Back to main Physics 2235 page