How can this code print such a large number? I have tried it on Ubuntu 14.04 (gcc 4.8.2). It does not work the same on MS Windows with any compiler (even MinGW, which is called "gcc for Windows"). Why?
#include <stdio.h>
#include <math.h>
int main()
{
printf("%.0f\n",pow(2,500));
}
Ubuntu output:
3273390607896141870013189696827599152216642046043064789483291368096133796404
674554883270092325904157150886684127560071009217256545885393053328527589376
Windows output:
3273390607896141900000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000
(The line break is added for clarity only.)
As hinted by OP and commented by @user300234, 2^500
is a 501 bit number, but that is not the issue here.
pow(2,500)
returns a double
, about 3.27e150
, which is typically a binary64. This type supports about 15 - 17 decimal digits of precision. So for numbers near 3.27e150
, printing more that 17 digits of significance is usually not important. It is well smaller than DBL_MAX
which may be about 1.798e308
.
The trick here is that pow(2,500)
is exactly representable as a floating point double
(binary64). This may give the illusion that a double
has hundreds of bits of precision - it does not.
The 2 different compilations handle conversion of double
to text in different ways, once 17 or so digits are printed - this is allowable by the C spec. The minimum number of correct digits is DBL_DECIMAL_DIG
- likely 17 on both systems.
Consider printing the next greater double
. Although the next double could be printed with 150 or so digits, typically these additional digits way pass DBL_DECIMAL_DIG
are simply noise for many applications.
// 2 ^ 500
327339060789614 187001318969682759915221664...
// next
327339060789614 259685191399243448970154045...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With