Integer Overflow

Skip Montanaro skip at pobox.com
Tue Nov 27 13:38:40 EST 2001


    >> Use longs:

    Ursus> Okay.  My next project was to do the same thing with 64-bit
    Ursus> numbers.  So how do I disable trapping for integer overflow?

    Ursus> (And don't tell me to use very longs ;-)

Python's long are already very long. ;-) To be precise, their size is
limited only by how much (virtual) memory you have available.  Example
(wrapped for readibility):

    >>> 3L**1000
    132207081948080663689045525975214436596542203275214816766492036822682
    859734670489954077831385060806196390977769687258235595095458210061891
    186534272525795367402762022519832080387801477422896484127439040011758
    861804112894781562309443806156617305408667449050617812548034440554705
    439703889581746536825491613622083026856377858229022841639830788789691
    855640408489893760937324217184635993869551676501894058810906042608967
    1438864102814350385648747165832010614366132173102768902855220001L
    >>> (3L**1000) % (2L**32)
    3552074529L

In the current 2.2 beta, int operations that would overflow silently return
longs:

    >>> 3**100
    515377520732011331036461129765621272702107522001L

You will have to force values back to ints when you know they will fit,
however.

    >>> (3**1000) % (2**31)
    1404590881L
    >>> int((3**1000) % (2**31))
    1404590881

I suggest you grab the latest beta and start having some fun...

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)




More information about the Python-list mailing list