【问题标题】:drawing a random number from a histogram从直方图中绘制一个随机数
【发布时间】:2014-12-16 18:43:41
【问题描述】:

我在从直方图中绘制随机数时遇到了一些麻烦。

如果我使用直方图来表示概率分布函数,我怎样才能有效地从该分布中生成 0 到 1 之间的 70128 个随机数,然后绘制它们?我还想要列表中的随机数,然后我可以稍后使用它们。

我的直方图代码如下所示:

`N = EU_Nodes(load_filename = "linear_gamma=1_B=0_A=0.7.npz")

def close(a,b):
    return ((a < (b*1.00001 + 1e-6)) and (a > (b* 0.99999 - 1e-6))) or (a==b)

def non_zeros(s):
    v=[]
    for w in s:
        if not close(w,0):
            v.append(w)
    return v

x0=-3
x1=3
b=np.arange(x0,x1,(x1-x0)/250.)

u=np.array(N[15].mismatch, dtype=np.float)
uu=np.array(sum(N[15].load)/70128, dtype=np.float)
uv=u/uu

plt.plot(b[0:-1], plt.hist(non_zeros(-uv), bins=b, normed=1, visible=0)[0], color = "k")`

【问题讨论】:

    标签: python random plot numbers histogram


    【解决方案1】:

    这是一个接受直方图和对应于每个直方图桶的值的类。 random 方法返回一个与直方图分布相同的随机值。

    import bisect
    import random
    
    def accumulate(iterable):
        ''' Produce an accumulated total of the input; adapted from Python 3 itertools.accumulate
        '''
        it = iter(iterable)
        total = next(it)
        yield total
        for element in it:
            total += element
            yield total
    
    class distrib:
        def __init__(self, hist, values):
            total = sum(hist)
            self.ranges = [accumulate(x/total for x in hist)]
            self.ranges[-1] = 1.0  # insure against roundoff error
            self.values = values
        def random(self):
            i = bisect.bisect_left(self.ranges, random.random())
            return self.values[i]
    

    【讨论】:

    • 好的,但是如何根据这些新的随机值绘制新的直方图?
    • @SmailKozarcanin 将它们放在一个列表中,并以与原始值相同的方式绘制它们。
    • 我不确定我是否理解代码,这就是为什么我不确定如何将新值放入列表中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 2013-07-23
    • 2021-04-19
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多