Math: Added solveQuadratic()

will be used in future for XP. This is extracted from the experience work branch.
This commit is contained in:
Dylan K. Taylor 2018-01-04 15:58:54 +00:00
parent 5c37d298a6
commit debfbf0d93

View File

@ -38,4 +38,30 @@ abstract class Math{
$i = (int) ($n + 1);
return $n >= $i ? $i : $i - 1;
}
/**
* Solves a quadratic equation with the given coefficients and returns an array of up to two solutions.
*
* @param float $a
* @param float $b
* @param float $c
*
* @return float[]
*/
public static function solveQuadratic(float $a, float $b, float $c) : array{
$discriminant = $b ** 2 - 4 * $a * $c;
if($discriminant > 0){ //2 real roots
$sqrtDiscriminant = sqrt($discriminant);
return [
(-$b + $sqrtDiscriminant) / (2 * $a),
(-$b - $sqrtDiscriminant) / (2 * $a)
];
}elseif($discriminant == 0){ //1 real root
return [
-$b / (2 * $a)
];
}else{ //No real roots
return [];
}
}
}