Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differing results from choice and choices in python random? [closed]

Tags:

python

I would have suspected the following code return comparable results:

import random

random.seed(765)
x = random.choices(range(34), k=100)

random.seed(765)
y = [random.choice(range(34)) for _ in range(100)]

But when we compare

>>> x[:5]
[1, 8, 9, 31, 29]
>>> y[:5]
[2, 30, 15, 26, 17]

clearly x is not equivalent to y.

I suspect that I a missing something obvious, but assumed the sequence set by the seed would have returned the same 100 values, regardless of choice vs choices with k = 100.

like image 391
Btibert3 Avatar asked Feb 07 '26 05:02

Btibert3


1 Answers

See the documentation:

For a given seed, the choices() function with equal weighting typically produces a different sequence than repeated calls to choice(). The algorithm used by choices() uses floating point arithmetic for internal consistency and speed. The algorithm used by choice() defaults to integer arithmetic with repeated selections to avoid small biases from round-off error.

like image 170
wjandrea Avatar answered Feb 09 '26 07:02

wjandrea



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!