比如以15%的概率生成数字0,以10%的概率生成数字1,以25%的概率生成数字2,以36%的概率生成数字3,以14%的概率生成数字4

代码如下

import random

def number_of_certain_probability(sequence, probability):
    x = random.uniform(0, 1)
    cumulative_probability = 0.0
    for item, item_probability in zip(sequence, probability):
        cumulative_probability += item_probability
        if x < cumulative_probability:
            break
    return item
# 测试代码
value_list = [0, 1, 2, 3, 4]
probability = [0.15, 0.1, 0.25, 0.36, 0.14]
zero = 0
one = 0
two = 0
three = 0
four = 0
for i in range(1000):
    result = number_of_certain_probability(value_list, probability)
    if result == 1:
        one = one + 1
    elif result == 0:
        zero = zero + 1
    elif result == 2:
        two = two + 1
    elif result == 3:
        three = three + 1
    elif result == 4:
        four = four + 1
print(zero, one, two, three, four)

结果

进行1000次试验,结果符合预期。

Last modification:November 11th, 2022 at 11:22 am
如果觉得我的文章对你有用,请随意赞赏