vendredi 9 juin 2017

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

I am trying to have a probability list, which I have to renew all the time when a new element joins. My code is:

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

Which yields:

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

And when I check the sum of the elements of prob_list, it sums up to 1 perfectly:

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

However, when I use this file in numpy.random.choice, it raises an error by saying that probabilities do not add up to 1:

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

The error is:

k = choice(my_list, size=1,replace=False, p=prob_list)[0] File "mtrand.pyx", line 1130, in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:17766)

ValueError: probabilities do not sum to 1

Do you know the reason of the error and how can I fix it?




Aucun commentaire:

Enregistrer un commentaire