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?
C++ POW(X,Y) X negative double and Y negative double, gives nan as result
951 views Asked by user3394626 At
3
There are 3 answers
2
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:
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.
I am guessing that you made a typo in SciLab. You must have written
Which means you did -(0.89 ^ -0.67) = -(1.08).
If you instead typed
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:output: