gpt4 book ai didi

c++ - 如何在 C++ 中添加两个大的 double

转载 作者:行者123 更新时间:2023-12-01 10:18:37 25 4
gpt4 key购买 nike

我有如下一段代码

#include <iostream>
#include <iomanip>

int main()

{
double x = 7033753.49999141693115234375;
double y = 7033753.499991415999829769134521484375;
double z = (x+ y)/2.0;

std::cout << "y is " << std::setprecision(40) << y << "\n";
std::cout << "x is " << std::setprecision(40) << x << "\n";
std::cout << "z is " << std::setprecision(40) << z << "\n";

return 0;
}

当上面的代码运行时,我得到,

y is 7033753.499991415999829769134521484375
x is 7033753.49999141693115234375
z is 7033753.49999141693115234375

当我在 Wolfram Alpha 中执行相同操作时,z 的值完全不同

 z = 7033753.4999914164654910564422607421875 #Wolfram answer

我熟悉浮点精度,无法精确表示远离零的大数。这就是这里发生的事情吗?无论如何,在 C++ 中我可以获得与 Wolfram 相同的答案而没有任何性能损失?

最佳答案

large numbers away from zero can not be exactly represented. Is that what is happening here?

是的。

请注意,还有无限多的有理数也无法在零附近表示。但可表示值之间的距离确实在较大的值范围内呈指数增长。

Is there anyway in c++ where I can get the same answer as Wolfram ...

使用 long double 可能会得到相同的答案。我的系统产生与 Wolfram 完全相同的结果。请注意,即使在符合 IEEE 754 标准的系统中,long double 的精度也会因系统而异。

但更一般地说,如果您需要精确到许多有效数字的结果,则不要使用有限精度数学。

... without any performance penalty?

没有。精度是有代价的。

关于c++ - 如何在 C++ 中添加两个大的 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58394120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com