Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sqrt() returns NAN

Tags:

php

nan

I've written a piece of code to carry out the quadratic equation:

function quadratic($a,$b,$c) {
    $mb = $b - ($b*2);
    $bs = $b * $b;
    $fac = ($a * $c) * 4;

    $ans1 = ($mb + sqrt(($bs - $fac))) / (2 * $a);
    $ans2 = ($mb - sqrt(($bs - $fac))) / (2 * $a);

    echo ("Your <b>+</b> value is: " . $ans1 . "<br />");
    echo ("Your <b>-</b> value is: " . $ans2);
}

The problem is that, if for example a=2, b=4, c=8, both answers are outputted as NAN. Any ideas as to how to fix this so that I get an actual number output?

like image 370
AviateX14 Avatar asked Dec 21 '22 01:12

AviateX14


1 Answers

   $a * $c * 4 = 64
   $bs = 4 * 4 = 16
   sqrt(($bs - $fac))) = sqrt(-48)

You cant take the sqrt of a negative number, it is not defined, hence the result is NaN.

Futhermore your formula can be simplified as:

 $mb = $b - ($b*2) = -$b

So instad of $mb you can simply use -$b.

Besides that, your formula is correct for the quadratic equation.

like image 59
thumbmunkeys Avatar answered Dec 24 '22 03:12

thumbmunkeys