Python random numbers in Jupyter

For many analyses, we are interested in calculating repeatable results. However, much of this analysis relies on some random numbers being used. In Python, you can set seed for the random number generator to achieve repeatable results with the random.seed() function.

In this example, we simulate rolling a pair of dice and look at the outcome. We would expect the average total of the two dice to be six, which is the half-way point between the faces.

The script we are using is as follows:

# using pylab statistics and histogram
import pylab
import random

# set random seed so we can reproduce results
random.seed(113)
samples = 1000

# declare our dataset store
dice = []

# generate and save the samples
for i in range(samples):
total = random.randint(1,6) + random.randint(1,6)
dice.append(total)

# compute some statistics on the dice throws
print("Throw two dice", samples, "times.")
print("Mean of", pylab.mean(dice))
print("Median of", pylab.median(dice))
print("Std Dev of", pylab.std(dice))

# display a histogram of the results
pylab.hist(dice, bins= pylab.arange(1.5,12.6,1.0))
pylab.xlabel("Pips")
pylab.ylabel("Count")
pylab.show()

Once we have the script in Jupyter and execute it, we will get the following result:

I added some more statistics. I'm not sure that I would have counted on such a high standard deviation. If we increased the number of samples, this would decrease.

The resulting graph was opened in a new window, much as it would if you ran this script in another Python development environment:

The graphic looks a little more jagged than I would have expected for a thousand samples.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.104.173