Numpy学习笔记三

范例随机漫步

import random
position=0
walk=[position]
steps=1000
for i in range(steps):
    step=1 if random.randint(0,1) else -1  #random.randint(0,1)随机产生0,1数字
    position+=step
    walk.append(position)
walk

np.random.seed(12345)
nsteps=1000
draws=np.random.randint(0,2,size=nsteps)
steps=np.where(draws>0,1,-1)
walk=steps.cumsum()
walk

walk.min(),walk.max(),(np.abs(walk)>=10).argmax() #(np.abs(walk) >= 10).argmax()找出第一个10或-10的索引值

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

walks.shape

#(np.abs(walks)>=30).any(1)每一行的1000列中若有一个值的绝对值小于30,则为true
hits30=(np.abs(walks)>=30).any(1)
hits30

hits30.shape

hits30.sum() #统计为true的数量

#计算在轴1上的平均穿越时间  
crossing_times=(np.abs(walks[hits30])>=30).argmax(1)
crossing_times,crossing_times.mean()

 

阅读更多

没有更多推荐了,返回首页