This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: random.randint fails for some ranges
Type: Stage:
Components: Library (Lib) Versions: Python 2.2
process
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: rhettinger Nosy List: phr, rhettinger
Priority: normal Keywords:

Created on 2004-02-20 19:27 by phr, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (4)
msg20080 - (view) Author: paul rubin (phr) Date: 2004-02-20 19:27
I want a random 32-bit int and do it the obvious way:

lowest, highest = int(-2**31), int(2**31-1)
r = random.randint(lowest, highest)

random.randint throws an exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python2.2/random.py", line 349, in randint
    return self.randrange(a, b+1)
  File "/usr/lib/python2.2/random.py", line 328, in
randrange
    raise ValueError, "empty range for randrange()"
ValueError: empty range for randrange()
msg20081 - (view) Author: paul rubin (phr) Date: 2004-02-21 08:16
Logged In: YES 
user_id=72053

It says "; current system time is also used to initialize
the generator when the module is first imported. "  That
sugests that the module is passing the current time to the
generator, rather than that the generator is initializing
itself with the current time.

Proposed new wording: ".  When a new generator is
instantiated, its inititialization method calls the seed
operation with a parameter of None.  The seed method then
uses the current time to initialize the generator as
described above.  If you subclass Random, your seed
operation can use some different method to create a default
seed on being initialized with None."
msg20082 - (view) Author: paul rubin (phr) Date: 2004-02-21 08:17
Logged In: YES 
user_id=72053

Oops, ignore previous comment, it was added to the wrong
bug.  Sorry.
msg20083 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2004-02-21 08:17
Logged In: YES 
user_id=80475

This has been fixed for Py2.3.3 and 2.4 as a result of the
automatic conversion between ints and longs.

In 2.2, it is still possible, but the call to int() inside
random.randrange() would be have to be changed to math.floor() 
which can handle the full range.  As the comments indicate,
this was not worth a performance hit.

As a workaround, generate two 16 bit integers and then join
them with (a << 16) | b.  This ought to work for practical
purposes; however, the underlying generator may not be
strong enough to make this a theoretically reliable
transform (i.e. it may dramatically shorten the period of
the composite generator).
History
Date User Action Args
2022-04-11 14:56:02adminsetgithub: 39962
2004-02-20 19:27:29phrcreate