Size of integers (2**32-1)

John Machin sjmachin at lexicon.net
Tue Feb 5 08:05:26 EST 2002


On Tue, 05 Feb 2002 10:16:36 +0100, Thomas Guettler
<st-newsgroups at thomas-guettler.de> wrote:

>I have two python version installed:
>with the cygwin version "print 2**32-1" works
>but with the zope version I get OverFlowError.
>
>Background:
>I want to get a random 32-Bit integer like this randrange(0, 2*32-1)
>
>thomas
>

Do you mean 2**31-1? Putting it another way, do you want a 32-bit
signed integer or an unsigned one?

It would help if you looked at the version *numbers* of the two
Pythons that you have; you will probably find that the "cygwin
version" is 2.2 and the "zope version" is 2.1

The problem is that 2**32 won't fit in 32 bits; Pythons before 2.2
cracked an overflow exception, whereas 2.1 promotes the result to a
long integer. Further, even 2**32-1 won't fit in a Python plain
integer which is a *signed* 32-bit integer on most/many platforms,
including yours.

Here is a quote from the Language Reference manual, section 3.2
"""
Plain integers 
These represent numbers in the range -2147483648 through 2147483647.
(The range may be larger on machines with a larger natural word size,
but not smaller.) When the result of an operation would fall outside
this range, the exception OverflowError is raised.
"""
Yes, that's from the 2.2 version, and yes, it needs updating :-)

So ... if you really want the value 2**32-1 on older Pythons, you need
to say 2L**32-1

AND in any case it looks like you're plumb out of luck with
random.randrange() .... it seems to be expecting a plain integer ...

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
>>> import random
>>> random.randrange(2L**32-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "c:\python22\lib\random.py", line 287, in randrange
    istart = int(start)
OverflowError: long int too large to convert to int

Do you really need a 32-bit integer? Would you like to be (brace
yourself!) portable across Python versions and platforms? Try this:
>>> import sys
>>> print random.randrange(sys.maxint)
1632975901
>>> print random.randrange(sys.maxint)
156138328
>>> print random.randrange(sys.maxint)
67281065

Oh and we'd better read the doco carefully: randrange(x) is designed
to act like Python's built-in range function --- 0 <= randrange(x) <
x.

To obtain a random 32-bit unsigned integer, you will need
long(random.random() * 2L ** 32)







More information about the Python-list mailing list