c++ pow(2,1000) is normaly to big for double, but it#39;s working. why?(c++ pow(2,1000) 通常对于 double 来说很大,但它正在工作.为什么?)
问题描述
代码:
#iclude <math.h>
int main(){
double somenumber = pow(2, 1000);
printf("%lf
", somenumber);
return 0;
}
我得到了这个巨大的数字:10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
i get this huge number: 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
这显然对双倍来说太大了.它是如何工作的?
This is obviously to big for double. How it's working?
推荐答案
这显然对双倍来说太大了.它是如何工作的?
This is obviously to big for double. How it's working?
21000 在可以用双精度表示的数字范围内.所以这个数字对于双倍来说显然不算大.
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.
我怀疑您所说的太大"是指打印的位数远大于可以存储在双精度中的 16 位左右的数字.要求计算机打印超过 16 个十进制数字并没有错.错在假设那些额外的数字有任何意义.
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.
在这种特殊情况下,打印的数字完全正确.那是因为计算机特别对待 pow(2,some_int)
.2 的幂可以精确地表示为双精度数.用于计算精确整数值的十进制表示的算法将给出完全正确的十进制表示.
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.
除此之外,一切都结束了.更改您的程序,使其打印 3646 例如:
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
", somenumber);
return 0;
}
它仍然会打印一个很大的长数字,但只有前 16 位左右的数字是正确的.
It will still print a big long number, but only the first 16 or so digits will be correct.
这篇关于c++ pow(2,1000) 通常对于 double 来说很大,但它正在工作.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++ pow(2,1000) 通常对于 double 来说很大,但它正在工作.为什么?
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01