MTH 337: Week 12

In [1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
In [2]:
from numpy.random import rand

Exercise 4: Sums of Random Variables

Sums of two uniform random numbers

In [3]:
plt.figure(figsize=(8,6))
npts = 10000
sums = np.sum(rand(2, npts), axis=0)
plt.hist(sums, bins=30, normed=True);

Sums of M-tuples of uniform random numbers

Note that as M increases, the distribution is getting wider in an absolute sense.

In [4]:
plt.figure(figsize=(15,3))
npts = 10000
for M in range(2, 7):
    sums = np.sum(rand(M, npts), axis=0)
    plt.subplot(1, 5, M-1)
    plt.hist(sums, bins=30, normed=True)
    plt.xlim(0, 6)
  • The histtype='step' keyword argument can be used to plot just the outline of a histogram.
  • Note that as M increases, the distribution is getting narrower in an relative sense.
  • Is the some scale, relative to which the histogram is getting neither wider or narrower?
In [5]:
plt.figure(figsize=(15,3))
npts = 10000
for M in range(2, 7):
    sums = np.sum(rand(M, npts), axis=0)
    plt.subplot(1, 5, M-1)
    plt.hist(sums, bins=30, normed=True, histtype='step')
    plt.xlim(0, M)

Exercise 5: The Exponential Distribution

Generating samples from a non-uniform distribution

In [6]:
u = rand(100000)
v = 2*u**(1/3)
plt.hist(v, normed=True, bins=50, fc='c')
x = np.linspace(0, 2)
y = 0.375*x**2
plt.plot(x, y, 'r', lw=2);

The exponential distribution for Carbon-14 → Nitrogen-14 decay

In [7]:
plt.figure(figsize=(10,5))
lam = 1/8267
tmax = 50000
t = np.linspace(0, tmax)
p = lam*np.exp(-lam*t)
plt.plot(t, p)
plt.xlim(0, tmax);

Exercise 6: To Switch or Not to Switch

In [8]:
from numpy.random import randint
In [9]:
randint(6)
Out[9]:
1
In [10]:
ngames = 10
winning = randint(1, 4, size=ngames)
print(winning)
[3 2 2 3 1 2 1 2 1 1]
In [11]:
chosen = np.ones(ngames, dtype=int)
print(chosen)
[1 1 1 1 1 1 1 1 1 1]
In [12]:
print(chosen == winning)
[False False False False  True False  True False  True  True]
In [13]:
print(np.mean(chosen == winning))
0.4
In [14]:
switched = np.where(winning==chosen, randint(2,4, size=ngames), winning)
In [15]:
print(np.mean(switched == winning))
0.6

Axis-Dependent Operations

In [16]:
a = np.array([1, 3])
print(a)
print(np.mean(a))
[1 3]
2.0
In [17]:
print(np.amin(a))
1
In [18]:
c = np.array([[1,2],[3,4]])
np.amin(c)
Out[18]:
1
In [19]:
np.amin(c, axis=1)
Out[19]:
array([1, 3])
In [20]:
print(np.mean(c, axis=0))
[ 2.  3.]

Exercise 7: Stock Market Simulation

In [21]:
from numpy.random import randn
In [22]:
mu = 0.0
sigma = 0.05
tmax = 366
s = 1
prices = np.empty(tmax)
prices[0] = s
for t in range(1, tmax):
    s *= 1 + mu + sigma*randn()
    prices[t] = s
plt.plot(prices);