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
01.
/**
02.
* Solves quadratic equation in form
03.
* ax^2 + bx + c = 0
04.
* @param a
05.
* @param b
06.
* @param c
07.
* @return array of real valued roots, null - if the equation has no real valued solution
08.
*/
09.
public
static
double
[] solveQuadraticEquation(
double
a,
double
b,
double
c) {
10.
double
d = b*b -
4
*a*c;
//discriminant
11.
if
(d <
0
) {
12.
return
null
;
13.
}
else
if
(d ==
0
) {
14.
double
[] result = {-b/
2
*a};
15.
return
result;
16.
}
else
{
17.
double
[] result = {(-b + Math.sqrt(d))/(
2
*a), (-b - Math.sqrt(d))/(
2
*a)};
18.
return
result;
19.
}
20.
}
01.
/**
02.
* Solves quadratic equation in form
03.
* ax^2 + bx + c = 0
04.
* @param a
05.
* @param b
06.
* @param c
07.
* @return array of real valued roots, null - if the equation has no real valued solution
08.
*/
09.
public
static
double
[] SolveQuadraticEquation(
double
a,
double
b,
double
c)
10.
{
11.
double
d = b * b - 4 * a * c;
//discriminant
12.
if
(d < 0)
13.
{
14.
return
null
;
15.
}
16.
else
if
(d == 0)
17.
{
18.
double
[] result = { -b / 2 * a };
19.
return
result;
20.
}
21.
else
22.
{
23.
double
[] result = { (-b + Math.Sqrt(d)) / (2 * a), (-b - Math.Sqrt(d)) / (2 * a) };
24.
return
result;
25.
}
26.
}
01.
/**
02.
* Solves quadratic equation in form ax^2 + bx + c = 0
03.
* @param $a
04.
* @param $b
05.
* @param $c
06.
* @return array of real valued roots, NULL - if the equation has no real valued solution
07.
* @author Thomas (www.adamjak.net)
08.
*/
09.
function
solve_quadratic_equation(
$a
,
$b
,
$c
){
10.
$d
=
$b
*
$b
- 4*
$a
*
$c
;
//discriminant
11.
if
(
$d
< 0) {
12.
return
NULL;
13.
}
else
if
(
$d
== 0){
14.
$result
= (-
$b
/2*
$a
);
15.
return
$result
;
16.
}
else
{
17.
$result
= ((-
$b
+ sqrt(
$d
))/(2*
$a
) . (-
$b
- sqrt(
$d
))/(2*
$a
));
18.
return
$result
;
19.
}
20.
}