Python中随机跳频的仿真和直方图

时间:2016-06-07 13:36:26

标签: python python-2.7 random histogram simulation

我向你解释我的问题:

想象一下,你有一个酒吧,有说明的位置。每个位置可以计为位置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

我的问题是,从我获得的直方图中,这是做错事。实际上,直方图都偏向左侧,如果概率是随机的,那么这是不可能的。 此外,直方图并没有向我显示正确数量的粒子。

有谁知道出了什么问题?

由于

1 个答案:

答案 0 :(得分:1)

我不知道我是否帮助你,但是 你想看到这个而不是直方图吗?

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