c++ pow(2,1000) is normaly to big for double, but it's working. why?

烂漫一生 提交于 2019-11-30 08:06:11

问题


the code:

#iclude <math.h>

int main(){
double somenumber = pow(2, 1000);
printf("%lf\n", somenumber);
return 0;
}

i get this huge number: 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

This is obviously to big for double. How it's working?


回答1:


This is obviously to big for double. How it's working?

21000 is within the range of numbers that can be represented by a double. So this number obviously is not too big for a double.

I suspect that what you mean by "too big" is that the number of digits printed is much greater than the 16 or so digits that can be stored in a double. There's nothing wrong with asking a computer to print more than 16 decimal digits. What's wrong is assuming that those extra digits have any meaning.

In this particular case, the printed number is exactly correct. That's because the computer treats pow(2,some_int) specially. Powers of 2 can be represented exactly in a double. The algorithm used to compute the decimal representation of an exact integral value will give the exactly correct decimal representation.

Anything else, all bets are off. Change your program so it prints 3646 for example:

#include <math.h>
#include <stdio.h>

int main(){
  double somenumber = pow(3, 646);
  printf("%lf\n", somenumber);
  return 0;
}

It will still print a big long number, but only the first 16 or so digits will be correct.




回答2:


double usually has 11bit for exp (-1022~1023 normalized), 52bit for fact and 1bit for sign. Thus it's simply not too large. For more explanation, see IEEE 754 on Wikipedia




回答3:


It is a power of two, and the floating point are essentially stored as (multiples of) powers of two.

Similarly, in decimal system, it shouldn't surprise you that it takes very little room to represent 101000 precisely, but such a concise notation would not be possible for large powers of other values, like 31000 = 1322070819480806636890455259752144365965422032752148167664920368226828597346704899540778313850608061963909777696872582355950954582100618911865342725257953674027620225198320803878014774228964841274390400117588618041128947815623094438061566173054086674490506178125480344405547054397038895817465368254916136220830268563778582290228416398307887896918556404084898937609373242171846359938695516765018940588109060426089671438864102814350385648747165832010614366132173102768902855220001.



来源:https://stackoverflow.com/questions/7371928/c-pow2-1000-is-normaly-to-big-for-double-but-its-working-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!