2016-04-21 49 views
0

我想绘制点希望最终我可以得到一个概率密度函数模拟。我的代码是:spyder绘制点的pdf

import random 
import math 
from numpy import * 
from matplotlib.pyplot import * 
import matplotlib.pyplot as pl 


clock_offset=3000 

y=0 

p=0.50 

for i in range (40): 

    x = random.random() 
    if x < p: 
     clock_offset+=1 

     for 'bo' in (clock_offset,y): 
      y+=1 
     pl.plot(clock_offset,y,'bo') 
     pl.axis([2980, 3040, 0, 40]) 
     y=0 
    else: 
     clock_offset-=1 

     for 'bo' in (clock_offset,y): 
      y+=1 
     pl.plot(clock_offset,y,'bo') 
     pl.axis([2980, 3040, 0, 40]) 
     y=0 

问题是我不能写一个for循环,使得Y + = 1,当那个地方(clock_offset,Y)已经占据了点。任何解决方案

+0

你打算干什么?对于'clock_offset,y'中的'bo':y + = 1'没有任何意义。与它有关的字符串是什么? – Roberto

回答

0

我不确定你的代码应该做什么。但看看this answer of mine,这解释了如何获得一个分布上的随机数。贝娄我给你重写了那个C++代码到python中。

import random 
import math 
import numpy as np 
import matplotlib.pyplot as plt 


def GausPDF(x, a=1., b=2., c=3.): 
    return a*math.exp( -((x-b)*(x-b)/(2*c*c) )) 

def random_on_PDF(PDF, top, bottom, maxPDF): 
    x = (top-bottom)*np.random.random()+bottom 
    y = maxPDF*random.random() 

    while(y>PDF(x)): 
     x = (top-bottom)*np.random.random()+bottom 
     y = maxPDF*random.random() 

    return x,y 


x, y, = list(), list() 
for i in range(0, 1000): 
    a,b = random_on_PDF(GausPDF, 10., -5., 1.) 
    x.append(a) 
    y.append(b) 

plt.scatter(x,y) 
plt.show() 

直接使用此代码和THIS matplotlib例如,您可以模拟投票如何随机影响/生成一个PDF。

这就是你所追求的?