import numpy as np
def randdist(x, pdf, nvals):
"""Produce nvals random samples from pdf(x), assuming constant spacing in x."""
# get cumulative distribution from 0 to 1
cumpdf = np.cumsum(pdf)
cumpdf *= 1/cumpdf[-1]
# input random values
randv = np.random.uniform(size=nvals)
# find where random values would go
idx1 = np.searchsorted(cumpdf, randv)
# get previous value, avoiding division by zero below
idx0 = np.where(idx1==0, 0, idx1-1)
idx1[idx0==0] = 1
# do linear interpolation in x
frac1 = (randv - cumpdf[idx0]) / (cumpdf[idx1] - cumpdf[idx0])
randdist = x[idx0]*(1-frac1) + x[idx1]*frac1
return randdist
正如弗朗西斯所说,你最好知道你的发行版的cdf。 无论如何,scipy提供了一种方便的方法来定义自定义发行版。 看起来很像
如果不使用scipy并给定PDF的数值采样,则可以使用累积分布和线性插值进行采样。下面的代码假设x的间距相等。可以修改它来对任意采样的PDF进行集成。请注意,它将PDF重新规范化为x范围内的1
相关问题 更多 >
编程相关推荐