从直方图中随机抽取一个数字
我在从直方图中随机抽取数字时遇到了一些问题。
如果我用直方图来表示一个概率分布函数,我该如何高效地从这个分布中生成70128个介于0和1之间的随机数字,并且之后还能把它们画出来?我还想把这些随机数字放在一个列表里,这样我可以后续使用。
我的直方图代码是这样的:
`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")`
1 个回答
0
这里有一个类,它接收一个直方图和与每个直方图桶对应的值。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]