import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
a = np.random.random_integers(1, 6, 4000)
a
array([2, 5, 2, ..., 5, 1, 1])
allprobs = []
for i in range(300):
a = np.random.random_integers(1, 6, 4000)
allprobs.append(len([x for x in a.reshape(-1, 4) if 6 in x]) / 1000.0)
plt.hist(allprobs)
(array([ 4., 16., 20., 36., 69., 73., 39., 32., 3., 8.]), array([ 0.468 , 0.4777, 0.4874, 0.4971, 0.5068, 0.5165, 0.5262, 0.5359, 0.5456, 0.5553, 0.565 ]), <a list of 10 Patch objects>)
trials = 500
overall = []
for t in range(trials):
initial = [20]
time = 200
for i in range(time):
if np.random.random() > 0.5:
initial.append(initial[-1] + 1)
else:
initial.append(initial[-1] - 1)
if initial[-1] == 0:
break
if len(initial) < 201:
initial += [0] * (201 - len(initial))
overall.append(initial)
b = np.linspace(0, 200, 201)
for o in overall:
plt.plot(b, o)
ends = []
for o in overall:
ends.append(o[-1])
plt.hist(ends, 66)
(array([ 86., 0., 3., 0., 9., 0., 13., 0., 20., 0., 20., 0., 21., 0., 22., 0., 29., 0., 26., 0., 25., 0., 20., 0., 28., 0., 32., 0., 23., 0., 23., 0., 16., 0., 18., 0., 12., 0., 12., 0., 11., 0., 6., 0., 10., 0., 5., 0., 1., 0., 4., 0., 3., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 1.]), array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66.]), <a list of 66 Patch objects>)
import math
xsgood = []
ysgood = []
xsbad = []
ysbad = []
good = 0
trials = 5000
for i in range(trials):
x = np.random.random()
y = np.random.random()
if (math.sqrt(x ** 2 + y ** 2) <= 1):
good += 1
xsgood.append(x)
ysgood.append(y)
else:
xsbad.append(x)
ysbad.append(y)
print(4 * float(good) / trials)
3.1616
fig = plt.gcf()
ax = fig.add_subplot(111, aspect='equal')
plt.plot(xsgood, ysgood, "o")
plt.plot(xsbad, ysbad, "o")
[<matplotlib.lines.Line2D at 0x113b62e90>]
endx = []
endy = []
trials = 10000
for i in range(trials):
x = 0
y = 0
steps = 1000
for i in range(steps):
r = np.random.random_integers(1, 4)
if r == 1:
x += 1
elif r == 2:
x -= 1
elif r == 3:
y += 1
elif r == 4:
y -= 1
endx.append(x)
endy.append(y)
len(endx), len(endy)
(10000, 10000)
plt.scatter(endx, endy)
<matplotlib.collections.PathCollection at 0x113c7d7d0>
x = [0]
y = [0]
steps = 10000
for i in range(steps):
r = np.random.random_integers(1, 4)
if r == 1:
x.append(x[-1] + 1)
y.append(y[-1])
elif r == 2:
x.append(x[-1] - 1)
y.append(y[-1])
elif r == 3:
x.append(x[-1])
y.append(y[-1] + 1)
elif r == 4:
x.append(x[-1])
y.append(y[-1] - 1)
plt.plot(x, y)
plt.plot(0, 0, "go")
plt.plot(x[-1], y[-1], "ro")
[<matplotlib.lines.Line2D at 0x114e1be10>]