为什么cmath pow给出不正确的答案? [英] Why does cmath pow give inaccurate answers?

查看:150
本文介绍了为什么cmath pow给出不正确的答案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11中:

pow(1061,6);   // = 1426567426713180416

检查最后3位数字。
我肯定知道结果是错误的,因为1061 ^ 6 = 1426567426713180361。

Check the last 3 digits. I know for sure that result is wrong, because 1061^6 = 1426567426713180361.

但是另一种方法做对了:

But this other method does it right:

long a =1;    
for(int i=0; i<6 ; i++){ a*=1061; }
cout << a;  // = 1426567426713180361

pow包含在cmath中。

pow is included from cmath.

如果有人知道,我想知道为什么两个结果都不相等。

If anyone knows, I'd like to know why both results aren't equal.

推荐答案

std :: pow 对于整数情况将返回双精度,并且此在此处回答解释了第一个积分,在该积分中double不能再精确地表示每个积分都以 9007199254740993 在此之后,我们可能会有无法完全表示为整数的整数。

std::pow will return double for the integral case and this answer here explains the first integral where double can not longer exactly represent every integral starts at 9007199254740993 after this we may have integers that can not be exactly repsented exactly as a double.

我们可以使用以下事实更容易地看到这一点:统一初始化。使用您期望的结果,我们会看到:

We can see this more easily using the fact that narrowing conversions are ill-formed using uniform initialization. Using the results you desire we see that:

double d2{1426567426713180361};

是缩小的转换(

is a narrowing conversion (live godbolt)

error: constant expression evaluates to 9007199254740993 which cannot be narrowed to type 'double' [-Wc++11-narrowing]
double d1{9007199254740993} ;
        ^~~~~~~~~~~~~~~~

它不能精确表示。我们还可以看到,前面的数字也正在缩小转换范围:

since it can not be exactly represented. We can also see the number from earlier is also a narrowing conversion:

double d1{9007199254740993} ;

同时:

double d3{1426567426713180416};

不是。

这篇关于为什么cmath pow给出不正确的答案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆