Long int too large to convert?

Tim Peters tim.one at home.com
Wed Sep 12 22:38:25 CEST 2001


[fbasegmez]
> I got this error message and not sure what it means?
>
> >>> for i in xrange(1L, 5 * pow(10L, 40)):
> ... 	x = i * x
> ...
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> OverflowError: long int too large to convert
> >>>

Python has two kinds of integers, ints and longs.  longs are unbounded; ints
are the same size as signed C longs on your box, most often 32 bits.  xrange
is restricted to ranges with no more than sys.maxint elements.

> Any ideas?

i, limit = 1L, 5 * 10L**40
while i < limit:
    x = i * x
    ...
    i += 1

> First I was going to use scientific notation instead of pow(x, y) but
> then I decided not to because,
> >>> long(5e40)
> 50000000000000000310004322520389159747584L
> >>>
> I am aware of numerical precision issues but this still managed to
> surprise me.


>>> import math
>>> mantissa, exponent = math.frexp(5e40)
>>> mantissa  # The input is exactly equal to mantissa * 2**exponent
0.57397185098744508
>>> exponent
136
>>> mantissa * 2L**53 # 53 bits is all the mantissa holds
5169878828456423.0
>>> long(mantissa * 2L**53) << (exponent - 53)
50000000000000000310004322520389159747584L
>>>

IOW, the result you got is the best possible 754 double-precision
approximation to 5e40, and the exact decimal value of this approximation is

50000000000000000310004322520389159747584L

You can't do better than that with 53 bits of floating precision.  The
closest representable 754 doubles on each side are worse approximations to
5e40:

>>> 5169878828456422L << (exponent - 53)
49999999999999990638597765603355762098176L
>>> 5169878828456424L << (exponent - 53)
50000000000000009981410879437422557396992L
>>>





More information about the Python-list mailing list