Question

std::pow is fine for most combinations of base and exponent values.

However when the base is negative and fractional, std::pow keels over.

In the example below NaN is returned (as per definition), when the expected value is roughly: -1.2332863005546

#include <cmath>
#include <cstdio>

int main()
{
    double a = -1.1;
    double b =  2.2;
    double c = std::pow(a,b);
    printf("%5.2f ^ %5.2f = %25.10f\n",a,b,c);
    return 0;
}

My question is: Any ideas on how to develop a generic pow function that returns non-NaN values when the base is negative?

Update - There will always be a class of results that can only be expressed using complex numbers.

Was it helpful?

Solution

This is not the expected value. The expected value is the complex number 0.998 + 0.725i. If you define a and b as std::complex<double> it will work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top