-2

So one day I was experimenting (like any other good coder does), and I came up across this:

>>> 1e308
1e+308
>>> 1e309
inf

What is going on? First of all, 308’s factors are 2, 2, 7, and 11.

Farther investigation yields:

>>> 1.7976931348623158075e308 # No, I didn’t copy it incorrectly
1.797693134862315e+308
>>> 1.79769313486231581+308
inf

So what is going on? There doesn’t seem any relationship between an absurdly big number and an equally weird number with over 10 decimal places.

Also, all of this was using the repl python console, so others might be different.

Einsteinium
  • 94
  • 13

1 Answers1

3

A double-precision floating point number in IEEE-754 has an 11-bit exponent and a 53-bit mantissa. The 11-bit exponent means we get from 2**(-1023) to 2**+1023. 2**1023 happens to be 10**308.

You get about 3.23 bits per decimal digit. A 53-bit mantissa gives you about 17 digits of precision.

The largest number that fits in a double is, as you noticed, 1.7976931348623158075E+308.

I recommend https://en.wikipedia.org/wiki/IEEE_754 .

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Ah, but the precision is only 15 decimal places... – Einsteinium Mar 13 '21 at 02:54
  • 2
    OK, you get 15.9 digits. It's almost 16. Not 17. I exaggerated. – Tim Roberts Mar 13 '21 at 05:07
  • Also, why does it show 1. 7976931348623157E+308 when 1. 7976931348623158E+308 is perfectly possible? – Einsteinium Mar 16 '21 at 20:09
  • @Einsteinium 1.7976931348623158E+308 isn't "perfectly possible"; it's borderline. 1.7976931348623157e308 really is the biggest double value. But 1.7976931348623158e308 is close enough to it that it rounds down. But any bigger and things "round up to infinity". (In fact, 1.7976931348623158e308 is bigger than 1.7976931348623157e308 by just about half the distance to the next-lower number, which is 1.7976931348623155e308, so this all works out. Although, this is all probably more a function of your particular string-to-double conversion function, not IEEE-754 itself.) – Steve Summit Apr 13 '23 at 22:58
  • More information about this sort of thing (albeit for single precision) at [`strtof()` conversion error by more than 0.5 ULP](https://stackoverflow.com/questions/75227883). – Steve Summit Apr 13 '23 at 23:03