In [1]:
# Code attribution: Yiyin Shen, Tyler Caraza-Harter
# Imports
import numpy
import matplotlib.pyplot as plt
In [2]:
# Set the seed generate a sequence of random variables
rng = numpy.random.default_rng(seed = 42)
x = rng.random(1000)
plt.hist(x)
Out[2]:
(array([ 96., 122., 90., 94., 101., 100., 92., 107., 100., 98.]), array([0.00123306, 0.10102023, 0.2008074 , 0.30059456, 0.40038173, 0.5001689 , 0.59995606, 0.69974323, 0.7995304 , 0.89931756, 0.99910473]), <BarContainer object of 10 artists>)
In [3]:
# Repeat the same thing
rng = numpy.random.default_rng(seed = 42)
x = rng.random(1000)
plt.hist(x)
Out[3]:
(array([ 96., 122., 90., 94., 101., 100., 92., 107., 100., 98.]), array([0.00123306, 0.10102023, 0.2008074 , 0.30059456, 0.40038173, 0.5001689 , 0.59995606, 0.69974323, 0.7995304 , 0.89931756, 0.99910473]), <BarContainer object of 10 artists>)
In [4]:
# Generate a random integer
x = rng.integers(0, 10, 1000)
plt.hist(x)
Out[4]:
(array([ 89., 112., 89., 110., 108., 96., 91., 96., 95., 114.]), array([0. , 0.9, 1.8, 2.7, 3.6, 4.5, 5.4, 6.3, 7.2, 8.1, 9. ]), <BarContainer object of 10 artists>)
In [5]:
# Simulate 10 fair coins
x = rng.binomial(10, 0.5, 1000)
plt.hist(x, range(12))
max(x)
Out[5]:
10
In [6]:
# Simulate 10 biased coins (probability 0.8 heads)
x = rng.binomial(10, 0.8, 1000)
plt.hist(x, range(12))
max(x)
Out[6]:
10
In [7]:
# Simulate the first time a fair coin lands heads
x = rng.geometric(0.5, 1000)
plt.hist(x, range(max(x) + 1))
max(x)
Out[7]:
11
In [8]:
# Simulate the first time a biased coin (0.2 probability heads) lands heads
x = rng.geometric(0.2, 1000)
plt.hist(x, range(max(x) + 1))
max(x)
Out[8]:
38
In [9]:
# Simulate a fair die with 6 faces
x = rng.multinomial(100, [1/6] * 6, 10)
x
Out[9]:
array([[17, 17, 17, 17, 14, 18], [24, 16, 16, 14, 13, 17], [11, 16, 15, 21, 22, 15], [15, 15, 19, 14, 23, 14], [15, 12, 15, 25, 15, 18], [18, 13, 14, 22, 13, 20], [ 9, 18, 22, 15, 15, 21], [25, 17, 18, 15, 14, 11], [15, 15, 20, 19, 20, 11], [17, 15, 17, 18, 16, 17]], dtype=int64)
In [10]:
# Run all simulations, repeat only once
x = rng.multinomial(1000, [1/6] * 6)
x
Out[10]:
array([154, 171, 173, 151, 192, 159], dtype=int64)