Why does the following code behave as it does in C?
float x = 2147483647; //2^31
printf("%f\n", x); //Outputs 2147483648
Here is my thought process:
2147483647 = 0 1001 1101 1111 1111 1111 1111 1111 111
(0.11111111111111111111111)base2 = (1-(0.5)^23)base10
=> (1.11111111111111111111111)base2 = (1 + 1-(0.5)^23)base10 = (1.99999988)base10
Therefore, to convert the IEEE 754 notation back to decimal: 1.99999988 * 2^30 = 2147483520
So technically, the C program must have printed out 2147483520, right?
The value to be represented would be 2147483647. the next two values which can be represented this way are 2147483520 and 2147483648.
As the latter is closer to the unrepresentable “ideal one”, it gets used: in floating point, the values get rounded, not truncated.