In [1]: import random
In [2]: import numpy as np
In [3]: import matplotlib.pyplot as plt
In [4]: position = 0
In [5]: walk = [position]
In [6]: steps = 1000
In [7]: for i in range(steps):
...: step = 1 if random.randint(0, 1) else -1
...: position += step
...: walk.append(position)
...:
In [8]: plt.plot(walk[:100])
Out[8]: [<matplotlib.lines.Line2D at 0x13da0a58898>]
In [9]: plt.show()
In [34]: nsteps = 1000
In [35]: draws = np.random.randint(0, 2, size=nsteps)
In [36]: steps = np.where(draws > 0, 1, -1)
In [38]: walk = steps.cumsum()
In [39]: walk.min()
Out[39]: -34
In [40]: walk.max()
Out[40]: 14
In [41]: plt.plot(walk[:100])
Out[41]: [<matplotlib.lines.Line2D at 0x13da2c1aa90>]
In [42]: plt.show()
一次性模拟多次随机漫步
In [47]: nwalks = 5000
In [48]: nsteps = 1000
In [49]: draws = np.random.randint(0, 2, size=(nwalks, nsteps)) # 0或1
In [50]: steps = np.where(draws > 0, 1, -1)
In [51]: walks = steps.cumsum(1)
In [52]: walks
Out[52]:
array([[ 1, 0, 1, ..., 18, 17, 18],
[ -1, 0, 1, ..., -54, -55, -56],
[ 1, 2, 3, ..., 10, 9, 10],
...,
[ 1, 2, 3, ..., -16, -17, -16],
[ -1, 0, 1, ..., 14, 13, 14],
[ 1, 2, 3, ..., -8, -9, -8]], dtype=int32)
In [53]: walks.max()
Out[53]: 118
In [54]: walks.min()
Out[54]: -119
In [55]:
In [55]:
In [55]: hist30 = (np.abs(walks) >= 30).any(1)
In [56]: hist30
Out[56]: array([ True, True, False, ..., True, False, False])
In [57]: hist30.sum()
Out[57]: 3367
In [58]: np.abs(walks[hist30])
Out[58]:
array([[ 1, 0, 1, ..., 18, 17, 18],
[ 1, 0, 1, ..., 54, 55, 56],
[ 1, 2, 3, ..., 30, 31, 30],
...,
[ 1, 0, 1, ..., 6, 5, 4],
[ 1, 2, 3, ..., 2, 3, 4],
[ 1, 2, 3, ..., 16, 17, 16]], dtype=int32)
In [59]: np.abs(walks[hist30]) >= 30
Out[59]:
array([[False, False, False, ..., False, False, False],
[False, False, False, ..., True, True, True],
[False, False, False, ..., True, True, True],
...,
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False]])
In [60]: (np.abs(walks[hist30]) >= 30).argmax(1)
Out[60]: array([433, 337, 815, ..., 555, 603, 351], dtype=int64)
In [61]: crossing_times = (np.abs(walks[hist30]) >= 30).argmax(1)
In [62]: crossing_times.mean()
Out[62]: 504.25274725274727
网友评论