import numpy as np
samples = np.random.normal(size = (4,4))
samples
array([[-1.5229485 , 0.77679543, 1.52695935, 1.20236513],
[-0.47239924, -1.44597446, 0.53760123, -1.41085789],
[-1.47101701, 0.87100219, -0.3450734 , -0.08409622],
[ 1.12957323, -0.60525586, -0.07127617, 1.30273091]])
from random import normalvariate
N = 10000
%timeit samples = [normalvariate(0,1)for _ in range(N)]
22.1 ms ± 2.79 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit np.random.normal(size=N)
621 µs ± 33.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
np.random.seed(1234)
rng = np.random.RandomState(1234)
rng.randn(10)
array([ 0.47143516, -1.19097569, 1.43270697, -0.3126519 , -0.72058873,
0.88716294, 0.85958841, -0.6365235 , 0.01569637, -2.24268495])
import random
import matplotlib.pyplot as plt
position = 0
walk = [position]
steps = 1000
for i in range(steps):
step = 1 if random.randint(0,1) else -1
position += step
walk.append(position)
plt.plot(walk[:100])
[<matplotlib.lines.Line2D at 0x1c0679c3978>]

nsteps = 1000
draws = np.random.randint(0,2,size = nsteps)
steps = np.where(draws>0,1,-1)
walk = steps.cumsum()
walk.min()
0
walk.max()
55
(np.abs(walk)>=10).argmax()
13
nwalks = 5000
nsteps = 1000
draws = np.random.randint(0,2,size = (nwalks,nsteps))
steps = np.where(draws>0,1,-1)
walks = steps.cumsum(1)
walks
array([[ 1, 2, 3, ..., -26, -27, -28],
[ -1, -2, -3, ..., -12, -13, -12],
[ 1, 0, 1, ..., 46, 45, 44],
...,
[ -1, -2, -3, ..., 32, 33, 34],
[ -1, 0, 1, ..., -6, -5, -4],
[ -1, -2, -1, ..., -18, -19, -18]], dtype=int32)
walk.max()
55
walks.min()
-128
hits30 = (np.abs(walks)>=30).any(1)
hits30
array([ True, True, True, ..., True, False, True])
hits30.sum()
3367
crossing_times = (np.abs(walks[hits30]) >= 30).argmax(1)
crossing_times.mean()
510.07157707157705