为什么cmath pow给出不正确的答案?

编程入门 行业动态 更新时间:2024-10-24 16:30:15
本文介绍了为什么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给出不正确的答案?

本文发布于:2023-11-30 04:05:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648657.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不正确   答案   cmath   pow

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!