[英]Generate exponential distribution in Python
I'm aware of the random.expovariate
function but this is not what I need. 我知道random.expovariate
函数,但这不是我所需要的。 I'd like to generate a stream of length N
in which each element i
between 1
and M
is chosen with probability 1/(2^(i+1)) Thus,element 0
is chosen with probability 1/2, element 1
with probability 1/4, element 2 with probability 1/8, etc. 我想生成一个长度为N
的流,其中选择1
和M
之间的每个元素i
概率为1 /(2 ^(i + 1))。因此,选择元素0
概率为1/2,选择元素1
概率为概率1/4,元素2的概率为1/8,依此类推。
Is there any simple way to do that in python ? 有什么简单的方法可以在python中做到这一点吗?
the simple solution is to revert the function and predict the proba to find the number: 简单的解决方案是还原函数并预测proba来找到数字:
def generate():
proba = random.random()
max = 0
for i in range(1,M+1):
max += (1/2)**i
if(proba<= max):
return i-1
return generate()
if M is small the distribution is not converging and thus not all [0,1] is reacheable, so you just try again. 如果M小,分布将不会收敛,因此并非所有[0,1]都是可到达的,因此您只需重试即可。
a little test: 一点测试:
M = 10
res = [0 for i in range(M+1)]
for i in range(1000):
res[generate()]+=1
plt.plot([r/1000 for r in res])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.