php pow function returns NAN

702 views Asked by At

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 ?

2

There are 2 answers

4
Mark Baker On BEST ANSWER

After some consultation with the experts in Room #11, pow() won't work with the root of a negative number. Should the answer be 0.8215 or -0.8215?

Quirkily, using the ** (power) operator will work with the root of a negative number

echo -0.3741569180353 ** 0.2 ;

because ** has higher precedence than -, so effectively what you're doing is

echo -(0.3741569180353 ** 0.2) ;
0
axiac On

Given a a negative number, its powers to integer exponents are defined as follows:

  • a0 is 0 - usually treated as positive;
  • a1 is a - negative;
  • a2 is a*a - positive;
  • an 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