1

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

1 Answers1

9

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.

  • Can you please elaborate more? I couldn't grasp the precision part. – Shubham Bansal Aug 05 '17 at 14:09
  • 1
    a floating point number has a mantissa and an exponent. in base `10`, the number represented is ` * 10 ^ `. In base `2` (as computers use), it's ` * 2 ^ `. So your number will be stored as mantissa `1b` and exponent `11 1111 1111b`. In base `10`, multipying a number by `10` is equivalent to incrementing the exponent. The same holds for base `2` and multiplying a number by `2`. –  Aug 05 '17 at 14:13
  • @FelixPalmen I tried the `printf("%.0f",pow(2,1023));` on gcc & overflow occurred. What could be the reason? – J...S Aug 05 '17 at 15:20
  • But does it not sound like odd that is how printf() handle such a Big integer? I mean is there any internal implementation working there? – Shubham Bansal Aug 05 '17 at 15:21
  • 1
    @ShubhamBansal You mean for conversion to the decimal digits? Of course! There's some iterative algorithm doing that used by `printf()`, probably somewhat similar to the "famous" [double dabble](https://en.wikipedia.org/wiki/Double_dabble#C_implementation) (but this is for integers). –  Aug 05 '17 at 15:24
  • @J...S maybe a different representation of `double`? I can't really tell you, it works for me using `gcc` on a linux x86_64 machine. –  Aug 05 '17 at 15:26
  • @FelixPalmen Thanks for replying anyways. – J...S Aug 05 '17 at 15:30
  • @J...S-- `double` is only _required_ to be able to represent a value wih base 10 exponent of at least +37; here the exponent is much larger. An implementation may of course use wider `double` than the minimum requirement. – ad absurdum Aug 05 '17 at 15:33