0

The program

int main ()
{
    long long ll = LLONG_MAX;
    float f = ll;
    std::cout << ll << '\n';
    std::cout << std::fixed << f << '\n';
    return 0;
}

gives:

9223372036854775807
9223372036854775808.000000

How is it possible? If 23-bit mantissa can have only 8,388,607 maximum value, why does cout output a 64-bit number?

Oleksa
  • 635
  • 5
  • 15

2 Answers2

2

You stored 2^63-1 in a float, which was rounded to 2^63 = 9223372036854775808. The powers of 2 are exactly representable.

The nearest number which is exactly representable is 2^63 + 2^40 = 9223373136366403584.

  • Can you explain a bit why + 2^40 gives the next representable number? – Oleksa Sep 11 '20 at 19:08
  • @olekstolar: 63 - 23 = 40. –  Sep 11 '20 at 19:18
  • It doesn't explain for me. If exponent bits have a value of 63 and a mantissa has 1, how can the next representable be something else than 2*2^63 or 1*2^64? – Oleksa Sep 11 '20 at 19:45
  • @olekstolar: the decimal point is on the left. Check the definition of the mantissa. –  Sep 11 '20 at 19:47
1

long long for you is a 64 bit data type so that means LLONG_MAX has a value of 2^63 - 1. You are right in that this can't be stored in a float which only has 23 bits of mantissa, but 2^63, which is one more than LLONG_MAX is easily stored in a float. It stores 2 in the mantissa and 63 in the exponent and there you have it.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 3
    You probably mean 1.0000... in the mantissa, actually stored as .00000... –  Sep 11 '20 at 18:52
  • 1
    @YvesDaoust I'm ignoring how it's actually encoded. I'm just demonstrating that it isn't really anything to store a `2^63` in a float exactly. – NathanOliver Sep 11 '20 at 18:56