GCC C++ pow accuracy

后端 未结 1 582
长情又很酷
长情又很酷 2020-12-01 23:55

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

相关标签:
1条回答
  • 2020-12-02 00:36

    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:

    template<typename T>
    T square(T 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.

    0 讨论(0)
提交回复
热议问题