How is pow() calculated in C?

前端 未结 4 2143
慢半拍i
慢半拍i 2021-01-05 09:42

Our professor said that you can\'t calculate ab if a<0 using pow() because pow() uses natural logarithms to calculate it (ab

4条回答
  •  灰色年华
    2021-01-05 10:00

    Assuming an x86 series processor, pow is the equivalent of

    double pow(double base, double exp)
    {
       return exp2(exp * log2(base));
    }
    

    Where exp2 and log2 are CPU primitives for the exponential and logarithm operations in base 2.

    Different CPUs inherently have different implementations.

    In theory if you didn't have pow you could write:

    double pow(double base, double exponent)
    {
       return exp(exponent * log(base));
    }
    

    but this loses precision over the native version due to accumulative roundoff.

    And Dietrich Epp revealed I missed a bunch of special cases. Nevertheless I have something to say about roundoff that should be allowed to stand.

提交回复
热议问题