A quadratic equation is a second-degree polynomial equation in a single variable, represented as ax^2 + bx + c = 0, where a, b, and c are constants. Solving a quadratic equation involves finding the values of the variable x that satisfy the equation. In this article, we will explore different approaches to finding the roots of quadratic equations in PHP.
Table of Content
Using Quadratic Formula
The quadratic formula is a standard method for solving quadratic equations.
We can implement this formula in PHP to find the roots of a quadratic equation.
<?php
function solveQuadratic($a, $b, $c) {
$discriminant = $b**2 - 4*$a*$c;
if ($discriminant > 0) {
$root1 = (-$b + sqrt($discriminant)) / (2*$a);
$root2 = (-$b - sqrt($discriminant)) / (2*$a);
return [$root1, $root2];
} else if ($discriminant == 0) {
$root = -$b / (2*$a);
return [$root];
} else {
return []; // No real roots
}
}
// Driver code
$a = 1;
$b = -3;
$c = 2;
$roots = solveQuadratic($a, $b, $c);
echo "Roots: " . implode(', ', $roots);
?>
Output
Roots: 2, 1
Using Factoring
Factoring involves expressing the quadratic equation as the product of two linear factors. We can use this method for simple cases where factoring is straightforward.
<?php
function solveQuadratic($a, $b, $c) {
$roots = [];
if ($a != 0) {
$factor1 = -($b / (2*$a));
$factor2 = sqrt($b**2 - 4*$a*$c) / (2*$a);
$roots[] = $factor1 + $factor2;
$roots[] = $factor1 - $factor2;
} elseif ($b != 0) {
$roots[] = -$c / $b;
}
return $roots;
}
// Driver code
$a = 1;
$b = -3;
$c = 2;
$roots = solveQuadratic($a, $b, $c);
echo "Roots: " . implode(', ', $roots);
?>
Output
Roots: 2, 1