在Python中生成具有已知离散概率的随机数

2024-05-20 22:44:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想生成随机的数字三元组(h,v,d)。

在一些if语句之后,根据h,v的随机值生成d数

h和v是已知间隔内的整数

下面是一个代码示例:

l="low"
m="medium"
h="high"

for i in range (100):
   h=random.random()*3
   v=random.choice(['low', 'medium', 'high'])

   d1=1
   d1_2=random.randint(1,2)
   d1_3=random.randint(1,3)

   if 0<h<0.5 or h==0:
       if v==l:
           d=d1

       elif v==m:
           d=d1_2

       elif v==h:
           d=d1_3

d1的概率为83.3%,d1~2的概率为6.7%,d1~3的概率为10%

如何在Python中插入这些可能性???

非常感谢你提前。。。


Tags: 代码间隔if数字整数random语句概率
3条回答

你可以这样计算机会

83.3%

import random

rand = random.randint(100,10000) * 0.010

if rand <= 83.3:
    print('success: ' + str(rand))
else:
    print('failed: ' + str(rand))

示例结果

192:Desktop allendar$ python test.py
success: 35.7
192:Desktop allendar$ python test.py
success: 60.03
192:Desktop allendar$ python test.py
success: 51.97
192:Desktop allendar$ python test.py
success: 45.58
192:Desktop allendar$ python test.py
failed: 87.53
192:Desktop allendar$ python test.py
success: 33.11
192:Desktop allendar$ python test.py
success: 50.68
192:Desktop allendar$ python test.py
success: 81.8

所以如果我理解正确的话,你希望变量‘v’取d1的值,概率为0.833(比如p1),d1_2的值,概率为0.067(称为p2),d1_3的值,概率为0.1(p3)

为此,可以生成0到1之间的均匀分布数,并检查该数是否小于p1。如果是,那么就让它取第一个值。如果不是,则检查它是否小于p1+p2。如果是,那么就让它取第二个值。最后,如果这两种情况都不是,则使用最终值。一些简单的代码如下:

p_1 = 0.833
p_2 = 0.067
p_3 = 0.1
r = numpy.random.rand()
if r < p_1:
  v = d1
elif r < (p_1 + p_2):
  v = d1_2
else:
  v = d1_3

你想从你的列表中得到一个不同权重的随机元素,对吧?

def weighted_random(weights):
    number = random.random() * sum(weights.values())
    for k,v in weights.iteritems():
        if number < v:
            break
        number -= v
    return k

# the following values can be any non-negative numbers, no need of sum=100
weights = {'d1': 83.3,
           'd1_2': 6.7,
           'd1_3': 10.}

for i in xrange(10):
    print weighted_random(weights),

以指纹为例

d1 d1 d1 d1_2 d1 d1 d1 d1_3 d1 d1_2

相关问题 更多 >