PHP sqrt () returns NAN

I wrote a code snippet to execute a 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 responses are output as NAN. Any ideas on how to fix this to get the actual pin number?

+4
source share
3 answers

If you are interested in solving the "real number", see

 function quadratic($a,$b,$c) { $mb = $b - ($b*2); $bs = $b * $b; $fac = ($a * $c) * 4; $bsfac = $bs-$fac; if($bsfac < 0){ $bsfac *= -1; } $ans1 = ($mb + sqrt(($bsfac))) / (2 * $a); $ans2 = ($mb - sqrt(($bsfac))) / (2 * $a); echo ("Your <b>+</b> value is: " . $ans1 . "<br />"); echo ("Your <b>-</b> value is: " . $ans2); } 

* Rounding not included

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

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

Moreover, your formula can be simplified as:

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

So, instad $mb can just be used -$b .

In addition, your formula is correct for a quadratic equation.

+7
source

Try exchanging data on these lines.

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

Source: https://habr.com/ru/post/1400267/


All Articles