Frantisek
Frantisek

Reputation: 7693

PHP's pow() with a negative number as input doesn't work

PHP's pow() doesn't want to process the following:

 pow(-5,1/3);

While in fact it is supposed to work. How can I do this in PHP?

Upvotes: 4

Views: 1810

Answers (4)

nneonneo
nneonneo

Reputation: 179452

Mathematically -51/3 is defined as simply the cube root of -5, which is around -1.71.

However, there's no way to precisely represent 1/3 in floating point. So, you're asking PHP to calculate something like -50.33333333333333331482961.

Now, if that exponent's exact rational expansion has an even denominator, the result is purely imaginary. If the exact rational expansion has an odd denominator, the result is purely real. The problem is that it is impossible to determine whether the denominator is "even" or "odd" because of the inadequate precision.

So, PHP doesn't bother. It just tells you that you can't do it, and that's the end of the story.

Upvotes: 1

Dennis Hackethal
Dennis Hackethal

Reputation: 14285

As PeeHaa has pointed out, the docs state that for some exponents the results can be "weird".

Algebraically the following is valid:

-x^(p) == -1*(x^p)

You could use this as a workaround. Speaking in code:

$x = pow(5,1/3)*-1;

But be wary of exponents like n/m with m being an even number!

You could use the following function to cover that as well:

function real_pow($base, $exponent){
  if($base < 0){
    if($exponent >= 1) return pow($base * -1, $exponent) * -1;
    else{
      if(is_nan(pow($base, $exponent))) return false;
      else return pow($base, $exponent);
    }
  }else{
    return pow($base, $exponent);
  }
}

This function will return valid pow's if the result is not a complex number. If it is, it will return false.

Upvotes: 1

Voitcus
Voitcus

Reputation: 4446

$base=-5;
$exponent=1/3;

$result = ($base<0?-1:1)*pow(abs($base),$exponent);

It is not valid for exponents being rationals with even denominator because it produces a complex number which PHP does not handle. You can write your own class/functions or google it, there are some in the web, but I never tested.

Upvotes: 0

Horen
Horen

Reputation: 11382

You are basically taking the 3rd root of a negative number here.

This is not always possible in the real number space. So in some cases you would need an imaginary unit to solve that equation.

It seems as if php just outputs NAN for cases where the base is negative and the exponent < 1.

Upvotes: 3

Related Questions