如何保证list的内容总和为1?

How to ensure that the contents of the list will always sum up to 1?

我想要一个概率列表,当有新元素加入时我必须一直更新它。我的代码是:

sum=7
my_list = [2,2,2,1]
prob_list = list(map(lambda x: float(x/sum), my_list))

产生:

>>prob_list
[0.2857142857142857, 0.2857142857142857, 0.2857142857142857, 0.14285714285714285]

当我检查 prob_list 的元素总和时,它完美地加起来为 1:

0,2857142857142857+ 0,2857142857142857+ 0,2857142857142857+0,14285714285714285 = 1

但是,当我在 numpy.random.choice 中使用此文件时,它会提示概率加起来不等于 1:

k = choice(my_list, size=1,replace=False, p=prob_list)[0]

错误是:

k = choice(my_list, size=1,replace=False, p=prob_list)[0] 文件 "mtrand.pyx", 第 1130 行,在mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:17766)

ValueError:概率之和不等于 1

您知道错误的原因吗?我该如何解决?

您所有的证据都表明此函数的 numpy 实现已损坏。这几乎可以肯定是由于浮点数舍入,每当您尝试将一堆浮点数加在一起并期望它正好是一个整数(整数)时,这种情况就可能发生。回溯表明函数本身是用 C 编写的,也许从 C 到 Python 的转换并返回引入了另一种累积舍入误差的方式。解决方案是忘记 numpy 并将函数写在 python 中,像这样:

import random

def choice(x):
    r = random.randrange(sum(x))
    for a in x:
        r -= a
        if r < 0:
            return a

my_list = [11, 4, 2, 2, 1]  

for _ in range(10):
    print(choice(my_list))

此例程假定您提供了一个整数列表,并避免了所有浮点运算。

顺便说一句,我不知道为什么这个问题被否决了。这对我来说是个好问题。