Reputation: 81
How does the following program print the exact value of 2^1023 without having any precision loss in C language?
#include <stdio.h>
#include<math.h>
int main()
{
// Printing the value of 2 ^1023
printf("%.0f",pow(2,1023));
return 0;
}
Output: 89884656743115795386465259539451236680898848947115328636715040578866337902750481566354238661203768010560056939935696678829394884407208311246423715319737062188883946712432742638151109800623047059726541476042502884419075341171231440736956555270413618581675255342293149119973622969239858152417678164812112068608
Upvotes: 1
Views: 334
Reputation:
Powers of two require only a single bit of precision. The mantissa will be just 1
(which is equivalent to two to the power of zero).
Think about it: This is because the base of a binary representation is 2
. In a base 10
that you're used to as a human, any power of ten needs only a single digit, e.g. 1000000 = 1 * 10^6
.
Your exponent of 1023
has 10 bits in binary notation (11 1111 1111
), so as long as the representation of a double
on your implementation has at least 11 bits (one more is needed for the sign) for the exponent, it's no surprise this number can be represented exactly.
Upvotes: 9