[issue24567] random.choice IndexError due to double-rounding

STINNER Victor report at bugs.python.org
Fri Jul 10 02:13:31 CEST 2015


STINNER Victor added the comment:

> Victor, if people want to use getrandbits(), we should backport the Python3 code, not reinvent it from scratch.

Sorry, I don't understand your comment. Backport what? getrandbits() is available on Python 2 and Python 3, for Random and SystemRandom.

I propose to rewrite Random.randint() in random.py.

> Your "It doesn't handle negative numbers nor empty ranges" should be a hint about what a pain it is to rewrite everything wholesale to use a _fundamentally_ different method.

In fact, I didn't check if the my code works for negative numbers. A few more lines should be enough to handle them. I just wanted to show a short pseudo-code to discuss the idea.

I don't understand your point on the pain. It's easy to replace int(i * random.random()) with randint(0, i) (sorry, I'm too lazy to check if it should be i, i-1 or i+1 :-)).

The Glib library used floats in their g_rand_int_range() method, but the function now uses only integers. The GSL library also uses integers. I'm surprised that Python uses floats to generate random numbers. For me, they are less reliable than integers, I always fear a bias caused by complex rounding and corner cases.

Do other libraries and/or programming languages use float to generate a random integer?

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24567>
_______________________________________


More information about the Python-bugs-list mailing list