GCC C ++ pow精度 [英] GCC C++ pow accuracy

查看:316
本文介绍了GCC C ++ pow精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在一个计算竞赛,我注意到一个奇怪的错误。 pow(26,2)总是返回675,有时674?即使正确的答案是676.这些类型的错误也发生pow(26,3),pow(26,4)等
经过一些调试后的比赛后,我相信答案与事实int轮下。有趣的是,这种错误从来没有发生过我。计算机我在windows 8上运行mingw。GCC版本是相当新的,像2-3个月大,我相信。但是我发现如果我把o1 / o2 / o3优化标志这些错误会奇迹般地消失。

  #include< cmath> 
#include< iostream>

using namespace std;
int main(){
cout<<< pow(26,2)<
cout<< int(pow(26,2))<<< endl;
}

双打的结果很奇怪。

  double a = 26; 
double b = 2;
cout<< int(pow(a,b))<<< endl; #outputs 675
cout<< int(pow(26.0,2.0))<<< endl; #outputs 676
cout<< int(pow(26 * 1.00,2 * 1.00))<< #outputs 676


解决方案 pow 对两个浮点值操作,并且可以将一个浮点值提升到另一个。这是通过近似算法完成的,因为它需要能够处理从最小到最大的值。



由于这是一个近似算法,它有时会得到价值有点错了。在大多数情况下,这是OK。但是,如果你有兴趣得到确切的结果,不要使用它。



我强烈建议不要使用它作为整数。如果第二个操作数是已知的(在这种情况下为2),用更快的代码替换它并返回正确的值是很简单的。例如:

  int square(int x)
{
return x * x;
}

回答实际问题:有些编译器可以替换 pow 与其他代码,或者当一个或两个参数已知时一起消除它。这就是为什么你得到不同的结果。


So i was in a computing contest and i noticed a weird bug. pow(26,2) would always return 675, and sometimes 674? even though correct answer is 676. These sort of errors also occur with pow(26,3), pow(26,4) etc After some debugging after the contest i believe the answer has to do with the fact int rounds down. Interestingly this kind of error has never occured to me before. The computer i had was running mingw on windows 8. GCC version was fairly new, like 2-3 months old i believe. But what i found was that if i turned the o1/o2/o3 optimization flag on these sort of error would miraculously disappear. pow(26,2) would always get 676 aka correct answer Can anyone explain why?

#include <cmath> 
#include <iostream> 

using namespace std; 
int main() { 
    cout<<pow(26,2)<<endl; 
    cout<<int(pow(26,2))<<endl; 
}

Results with doubles are weird.

double a=26; 
double b=2; 
cout<<int(pow(a,b))<<endl; #outputs 675 
cout<<int(pow(26.0,2.0))<<endl; # outputs 676 
cout<<int(pow(26*1.00,2*1.00))<<endl; # outputs 676

解决方案

The function pow operates on two floating-point values, and can raise one to the other. This is done through approximating algorithm, as it is required to be able to handle values from the smallest to the largest.

As this is an approximating algorithm, it sometimes gets the value a little bit wrong. In most cases, this is OK. However, if you are interested in getting an exact result, don't use it.

I would strongly advice against using it for integers. And if the second operand is known (2, in this case) it is trivial to replace this with code that does this much faster and that return the correct value. For example:

int square(int x)
{
  return x * x;
}

To answer the actual question: Some compilers can replace calls to pow with other code, or eliminate it all together, when one or both arguments are known. This explains why you get different results.

这篇关于GCC C ++ pow精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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