What is the range of values a float can have in Python?
Python uses double-precision floats, which can hold values from about 10 to the -308 to 10 to the 308 power.
http://en.wikipedia.org/wiki/Double_precision_floating-point_format
Try this experiment from the Python prompt:
>>> 1e308
1e+308
>>> 1e309
inf
10 to the 309 power is an overflow, but 10 to the 308 is not. QED.
Actually, you can probably get numbers smaller than 1e-308 via denormals, but there is a significant performance hit to this. I found that Python is able to handle 1e-324
but underflows on 1e-325
and returns 0.0
as the value.
See this post.
Relevant parts of the post:
In [2]: import kinds In [3]: kinds.default_float_kind.M kinds.default_float_kind.MAX kinds.default_float_kind.MIN kinds.default_float_kind.MAX_10_EXP kinds.default_float_kind.MIN_10_EXP kinds.default_float_kind.MAX_EXP kinds.default_float_kind.MIN_EXP In [3]: kinds.default_float_kind.MIN Out[3]: 2.2250738585072014e-308
As a kind of theoretical complement to the previous answers, I would like to mention that the "magic" value ±308 comes directly from the binary representation of floats. Double precision floats are of the form ±c*2**q with a "small" fractional value c (~1), and q an integer written with 11 binary digits (including 1 bit for its sign). The fact that 2**(2**10-1) has 308 (decimal) digits explains the appearance of 10**±308 in the extreme float values.
Calculation in Python:
>>> print len(repr(2**(2**10-1)).rstrip('L'))
308
>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308,
min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15,
mant_dig=53, epsilon=2.2204460492503131e-16, radix=2, rounds=1)
The smallest is sys.float_info.min
(2.2250738585072014e-308) and the biggest is sys.float_info.max
(1.7976931348623157e+308). See documentation for other properties.
sys.float_info.min
is the normalized min. You can usually get the denormalized min as sys.float_info.min * sys.float_info.epsilon
. Note that such numbers are represented with a loss of precision. As expected, the denormalized min is less than the normalized min.