[Python-bugs-list] random.randint/randrange fails for large range (PR#80)

tim_one@email.msn.com tim_one@email.msn.com
Mon, 13 Sep 1999 21:34:13 -0400 (EDT)


[Jeremy Hylton]
> >>> x = 2**30
> >>> y = -2**30
> >>> random.randint(y, x)
> Traceback (innermost last):
> ...
> OverflowError: integer subtraction
>
> I think the solution is to change line 120 so that it performs all
> the calculations on longs and converts to int just before it returns.

I consider this an obscure way of spelling the truth:  "this algorithm is
too weak to produce acceptable results for a range that large".  I
personally don't trust whrandom to choose from a range larger than about
2**15 elements (already a bit beyond the resolution of its underlying
generators).

The other consideration is sane-case speed, so if it's decided to go ahead
and produce bogus results <wink>, better to wrap the method body in
try/except_OverflowError and bite the expense of the int->long->int business
only when necessary.

Overall, if something *needs* to be done here, documentation may be the best
answer.  Note that on a C-long==64-bits machine, it's easy to feed randint a
non-overflowing range larger than the resolution of a double, and randint
has no chance at all of producing a reasonable approximation to randomness
then.

IOW, numerical algorithms have limits, and those need to be documented, or
(preferably, but sometimes just too expensive to do so) enforced, or (best
of all, but very expensive and difficult) removed via much more elaborate
algorithms.