views:

101

answers:

1

Is there any way to check if a long integer is too large to convert to a float in python?

+13  A: 
>>> import sys
>>> sys.float_info.max
1.7976931348623157e+308

Actually, if you try to convert an integer too big to a float, an exception will be raised.

>>> float(2 * 10**308)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C double
KennyTM
For pedants: if you care about edge-cases, then the second method ('try it and see') is a bit more reliable. There are integers larger than sys.float_info.max (only by a tiny amount, though) that can still safely be converted to float. On a typical machine, `int(sys.float_info.max)` is `2**1024 - 2**971`, but integers up to and including `2**1024 - 2**970 - 1` can be converted without raising `OverflowError`.
Mark Dickinson