Hacker News new | ask | show | jobs
by IanCal 547 days ago
Yes but if you want to do things in a less obvious way you should be aware of the downsides, such as bias in your random numbers. Also making sure you watch out for off by one errors.

Stolen the number to show this off well from a bug report somewhere:

    random_counter = Counter()
    
    for i in range(10_000_000):
        result = floor(random() * 6755399441055744) % 3
        random_counter[result] += 1

    print("floor method", random_counter.most_common(3))

    randint_counter = Counter()
    
    for i in range(10_000_000):
        result = randint(0, 6755399441055743) % 3
        randint_counter[result] += 1

    print("randint method", randint_counter.most_common(3))

Result

    floor method [(1, 3751972), (0, 3333444), (2, 2914584)]
    randint method [(1, 3334223), (2, 3333273), (0, 3332504)]
https://bugs.python.org/issue9025
1 comments

Have you ran this in any modern version of Python? It’s been fixed for a long time.
3.10 so I redid it on 3.13.1, same results.
Ugh, I was checking `randrange` (as the bug mentions), not `random`. I stand corrected.
Ah yeah sorry I should have mentioned it wasn't the same, I used it as it has a nice number that shows the bias to a pretty extreme degree.