how can I use np.random.choice here?
there is p
that calculate by some opertation, like :
p=[ 1.42836755e-01, 1.42836735e-01 , 1.42836735e-01, 1.42836735e-01
, 4.76122449e-05, 1.42836735e-01 , 4.76122449e-05 , 1.42836735e-01,
1.42836735e-01, 4.76122449e-05]
usually sum p is not exact equal to 1:
>>> sum(p)
1.0000000017347
I want to make random choice by probabilities=p:
>>> np.random.choice([1,2,3,4,5,6,7,8,9, 10], 4, p=p, replace=False)
array([4, 3, 2, 9])
this work here! but in the program it has an error :
Traceback (most recent call last):
indexs=np.random.choice(range(len(population)), population_number, p=p, replace=False)
File "mtrand.pyx", line 1141, in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:17808)
ValueError: probabilities do not sum to 1
if I print the p
:
[ 4.17187500e-05 2.49937500e-01 4.16562500e-05 4.16562500e-05
2.49937500e-01 4.16562500e-05 4.16562500e-05 4.16562500e-05
2.49937500e-01 2.49937500e-01]
but it works, in python shell by this p
:
>>> p=[ 4.17187500e-05 , 2.49937500e-01 ,4.16562500e-05 , 4.16562500e-05,
2.49937500e-01 , 4.16562500e-05 , 4.16562500e-05 , 4.16562500e-05,
2.49937500e-01 ,2.49937500e-01]
>>> np.random.choice([1,2,3,4,5,6,7,8,9, 10], 4, p=p, replace=False)
array([ 9, 10, 2, 5])
UPDATE I have tested it by precision=15:
np.set_printoptions(precision=15)
print(p)
[ 2.499375625000002e-01 2.499375000000000e-01 2.499375000000000e-01
4.165625000000000e-05 4.165625000000000e-05 4.165625000000000e-05
4.165625000000000e-05 4.165625000000000e-05 2.499375000000000e-01
4.165625000000000e-05]
testing:
>>> p=np.array([ 2.499375625000002e-01 ,2.499375000000000e-01 ,2.499375000000000e-01,
4.165625000000000e-05 ,4.165625000000000e-05, 4.165625000000000e-05,
4.165625000000000e-05 , 4.165625000000000e-05 , 2.499375000000000e-01,
4.165625000000000e-05])
>>> np.sum(p)
1.0000000000000002
how fix this to use np.random.choice ?
[repr(x) for x in p]
and, ifp
is a numpy array,p.dtype
. Despite the common belief it is not always possible to recreate a sequence of floats just from the output ofprint
. – Leiva