Long int too large to convert?
tim.one at home.com
Wed Sep 12 22:38:25 CEST 2001
> 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)
> 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
>>> mantissa * 2L**53 # 53 bits is all the mantissa holds
>>> long(mantissa * 2L**53) << (exponent - 53)
IOW, the result you got is the best possible 754 double-precision
approximation to 5e40, and the exact decimal value of this approximation is
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
>>> 5169878828456422L << (exponent - 53)
>>> 5169878828456424L << (exponent - 53)
More information about the Python-list