When I execute
echo pow( -0.3741569180353 , 0.2 ) ;
I am getting result NAN
While in excel and calculator, I am getting the answer -0.8215.
What is the solution to fix this as I am having lot of such calculations ?
Given a
a negative number, its powers to integer exponents are defined as follows:
a
0
is 0
- usually treated as positive;a
1
is a
- negative;a
2
is a*a
- positive;a
n
is negative for odd values of n
and positive for even values of n
.The exponentiation of a negative base to a non-integer exponent is not defined in real numbers.
(It is, however, defined in complex numbers.)
The pow()
function is correct. It returns NaN
because the result is not a real number.
The behaviour is even specified in the Examples section of the documentation:
echo pow(-1, 5.5); // PHP >=5.2.2: NAN
After some consultation with the experts in Room #11,
pow()
won't work with the root of a negative number. Should the answer be0.8215
or-0.8215
?Quirkily, using the
**
(power) operator will work with the root of a negative numberbecause
**
has higher precedence than-
, so effectively what you're doing is