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

Simulation and Histogram of Random Hopping in Python

我给你解释一下我的问题:

假设你有一个酒吧,有 s 个位置。每个位置都可以算作位置0,位置1,..,位置s-1。 现在我想要做的是模拟以下内容:在某个时间点,一些粒子,比如 n 个粒子,开始处于条形状态(假设在中间的位置)。 此时以随机概率 pr 和 pl (pr + pl =1) 这个粒子分别向右或向左移动。所以基本上概率反映了粒子左右交换的比例。

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

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)