Quadratic equation with one unknown is an algebraic equation of the second order. It can written in the form , where x is the unknown and a, b, c are real valued constants. Provided , the equation is linear.
Quadratic equation can be visualized as a parabola. When a is positive, than the parabola is convex, when negative, the parabola is concave.
Solving quadratic equation
At first, we have to calculate so called discriminant:
If the discriminant is negative, than the equation has no real solution (root), but has two distinct imaginary roots.
If the discriminant is equal to zero, than the equation has one real solution:
If the discriminant is positive, than the equation has two distinct real roots:
Example
Find roots of the equation .
First of all, we calculate the discriminant.
Because the discriminant is positive, the equation has two real roots. By plugging the discriminant into the above mentioned formula, we get:
Code
/** * Solves quadratic equation in form * ax^2 + bx + c = 0 * @param a * @param b * @param c * @return array of real valued roots, null - if the equation has no real valued solution */ public static double[] solveQuadraticEquation(double a, double b, double c) { double d = b*b - 4*a*c; //discriminant if(d < 0) { return null; } else if (d == 0) { double[] result = {-b/2*a}; return result; } else { double[] result = {(-b + Math.sqrt(d))/(2*a), (-b - Math.sqrt(d))/(2*a)}; return result; } }
/** * Solves quadratic equation in form * ax^2 + bx + c = 0 * @param a * @param b * @param c * @return array of real valued roots, null - if the equation has no real valued solution */ public static double[] SolveQuadraticEquation(double a, double b, double c) { double d = b * b - 4 * a * c; //discriminant if (d < 0) { return null; } else if (d == 0) { double[] result = { -b / 2 * a }; return result; } else { double[] result = { (-b + Math.Sqrt(d)) / (2 * a), (-b - Math.Sqrt(d)) / (2 * a) }; return result; } }
/** * Solves quadratic equation in form ax^2 + bx + c = 0 * @param $a * @param $b * @param $c * @return array of real valued roots, NULL - if the equation has no real valued solution * @author Thomas (www.adamjak.net) */ function solve_quadratic_equation($a, $b, $c){ $d = $b*$b - 4*$a*$c; //discriminant if($d < 0) { return NULL; } else if ($d == 0){ $result = (-$b/2*$a); return $result; } else { $result = ((-$b + sqrt($d))/(2*$a) . (-$b - sqrt($d))/(2*$a)); return $result; } }