C++ POW(X,Y) X negative double and Y negative double, gives nan as result

951 views Asked by At

I'm trying to do a simple operation, pow(-0.89,-0.67) in my C++ 14 code, and it gives a NaN as result. When doing the same in SciLab the result is -1.08. Is there any way in C++ to get the right result?

3

There are 3 answers

1
rlbond On BEST ANSWER

I am guessing that you made a typo in SciLab. You must have written

-0.89 ^ -0.67

Which means you did -(0.89 ^ -0.67) = -(1.08).

If you instead typed

(-0.89) ^ -0.67

You would have gotten the answer -0.5504 - 0.9306i. The negative root of a negative number is complex, and the pow function in C++ will give you a NaN result.

If you use the std::complex type, you will get the correct answer of -0.5504 - 0.9306i:

#include <iostream>
#include <complex>
#include <cmath>

int main()
{
    std::complex<double> a(-0.89), b(-0.67);
    std::cout << std::pow(a,b) << std::endl; 
}

output:

(-0.550379,-0.93064)
2
gsamaras On

From the documentation of pow(), you have:

If base is negative and exponent is not an integral value, or if base is zero and exponent is negative, a domain error occurs, setting the global variable errno to the value EDOM.

So, the nan result you are getting is expected.


You could do it like this:

printf ("-0.89 ^ -0.67 = %f\n", -pow (0.89,-0.67) );

which gives:

-0.89 ^ -0.67 = -1.081207


Links I was based into:

  1. c++ pow function- invalid result?
  2. pow() problem

Nice question, +1!

0
Огњен Шобајић On

It's always good to consult the standard: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf It says:

— pow(x, y) returns a NaN and raises the ‘‘invalid’’ floating-point exception for finite x < 0 and finite non-integer y.

Therefore, your C++ compiler is right. It should return NaN.