Python中随机跳跃的模拟和直方图



我向您解释我的问题:

想象一下,你有一个酒吧,有发言权。每个位置可以被计数为位置0、位置1、..、.、.、,位置s-1。现在我想做的是模拟以下内容:在某个时间点,许多粒子,比如n个粒子,开始于条的状态(假设在中间的位置)。在随机概率为pr和pl(pr+pl=1)的这一点上,粒子分别向右或向左移动。因此,概率基本上反映了粒子左右交换的比例。

我想重复多次,看看粒子的最终位置是什么,并绘制它的直方图。这是我的函数跳跃,我做它是为了模拟粒子的跳跃。

def hop(n):
'''
n is the number of particles starting in the middle position.
'''
s = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,n,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
global ls
ls = len(s)
i = 0
while i < 100:
for j in range(0,int(len(s))):
if s[j] != 0 :
pr = random.random()
pl = 1 - pr
if j - 1 < 0:
s[j+1] = s[j+1]+int(s[j]*pr)
s[j] = s[j] - int(s[j]*pr)
elif len(s) <= j+1:
s[j-1] = s[j-1] + int(s[j]*pl)
s[j] = s[j] - int(s[j]*pl)
else:
s[j-1] = s[j-1] + int(s[j]*pl)
s[j+1] = s[j+1] + int(s[j]*pr)
s[j] = s[j] - int(s[j]*pr) - int(s[j]*pl)
j+=1
elif s[j] == 0:
s[j] = 0
j+=1
i+=1
return s

这是我用来绘制直方图的其余部分:

x = hop(100)
y = sum(x) #This is for debugging purposes, I want to check that I'm left 
with the right number of particles
list1 = []
for k in range(0,ls):
list1.append(k)
plt.hist(x,list1)
plt.show()

我在哪里导入了mathplotlib,特别是导入了

import matplotlib.pyplot as plt
import random

我的问题是,从我获得的直方图来看,这是在做一些非常错误的事情。事实上,直方图都向左倾斜,如果概率是随机的,这是不可能的。此外,直方图没有显示正确的粒子数量。

有人知道出了什么问题吗?

感谢

我不知道你说得对不对,但是你想看这个而不是直方图吗?

xs = np.arange(len(x))
width = 1/1.5
plt.bar(xs,x,width)

最新更新