Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random.choices() in python

Tags:

python

random

I'd like to confirm that

a = [random.choices([0,1],weights=[0.2,0.8],k=1) for i in range(0,10)] 

does probabilistically the same thing as

a = random.choices([0,1],weights=[0.2,0.8],k=10) 

In particular, I expect both to make 10 independent draws from the set {0,1} with probability 0.2 on 0 and 0.8 on 1. Is this right?

Thanks!

like image 431
strawberrycello Avatar asked Jan 20 '26 03:01

strawberrycello


1 Answers

The documentation seems to indicate the two are probabilistically the same and after running the following experiment:

from collections import defaultdict
import pprint
import random

results1 = defaultdict(int)
results2 = defaultdict(int)

for _ in range(10000):
    a = [random.choices([0,1],weights=[0.2,0.8],k=1) for i in range(0,10)]
    for sublist in a:
        for n in sublist:
            results1[n] += 1

for _ in range(10000):
    a = random.choices([0,1],weights=[0.2,0.8],k=10)
    for n in a:
        results2[n] += 1


print('first way 0s: {}'.format(results1[0]))
print('second way 0s: {}'.format(results2[0]))
print('first way 1s: {}'.format(results1[1]))
print('second way 1s: {}'.format(results2[1]))

I am seeing very similar results between the two methods.

like image 178
kingkupps Avatar answered Jan 21 '26 16:01

kingkupps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!