1. 程式人生 > >Python隨機漫步

Python隨機漫步

#時間漫步
import numpy as np
from numpy import linalg
import random
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)
# print(walk)
nsteps=1000
draws =np.random.randint(0,2,size=nsteps)
steps=np.where(draws>0,1,-1)
walk=steps.cumsum()
(np.abs(walk)>=10).argmax()

nwalks=5000
nsteps=1000
draws=np.random.randint(0,2,size=(nwalks,nsteps))
steps=np.where(draws>0,1,-1)
walks=steps.cumsum(1)
print(walks)
hits30=(np.abs(walks)>=30).any(1)
print(hits30)
hits30.sum()