Java Snippets Roots of a quadratic equation

The discriminant of a polynomial is a function of its coefficients, typically denoted by a capital D or the capital Greek letter Delta (Δ). It gives information about the nature of its roots. For example, the discriminant of the quadratic polynomial:

is

$\Delta ={b}^{2}-4ac$

This java class has a function called discriminant2n() to calculate the discriminant:

public static double discriminant2n(double a, double b, double c) {
double d =  b*b - 4*a*c ;
return d;
}

so that we can call it like this:

d = discriminant2n(a, b, c);

and a function calculateRoots() to calculate the actual roots. For real a, b and c, the solution to the quadratic equation is:

$x=\frac{-b±\sqrt{{b}^{2}-4ac}}{2a}=\frac{-b±\sqrt{\Delta }}{2a}$

There are three cases: 1. If Δ = 0, the polynomial has one real double root:
2. ${x}_{1}={x}_{2}=\frac{-b}{2a}$

which is calculated as r0 so that it can be reused in the other two calculations:

r0 = - b / (2*a);

if (d == 0) {
System.out.println("\nThe discriminant is zero. The only root of the quadratic equation is r = " + Commons.twoDecimals(r0) + ".\n");
}

The function Commons.twoDecimals prints the number with a point and two decimals (see Commons).

3. If Δ > 0, the polynomial has two real roots:
4. $\frac{-b+\sqrt{\Delta }}{2a}$ and $\frac{-b-\sqrt{\Delta }}{2a}$

so we take the previously calculated r0 value and add and substract the square root of the discriminant divided by 2a:

else if (d > 0) {
r = r0 + ( Math.sqrt(d) / (2*a) );
System.out.print("\nThe discriminant is positive. The roots of the quadratic equation are r1 = " + Commons.twoDecimals(r) );

r = r0 - ( Math.sqrt(d) / (2*a) );
System.out.println(" and r2 = " + Commons.twoDecimals(r) + ".\n");
}
5. If Δ < 0, the polynomial has no real roots. The solutions are:
6. $\frac{-b}{2a}+\frac{\sqrt{-}\Delta }{2a}$ and $\frac{-b}{2a}-\frac{\sqrt{-}\Delta }{2a}$

which can also be written as:

$\frac{-b}{2a}+\frac{\sqrt{\Delta }}{2a}i$ and $\frac{-b}{2a}-\frac{\sqrt{\Delta }}{2a}i$

since $i=\sqrt{-1}$ and $\sqrt{-\Delta }=\sqrt{-1}\sqrt{\Delta }=i\sqrt{\Delta }$. So we take r0 and calculate r as $\frac{\sqrt{\Delta }}{2a}$ and print it as r0 + r i

else if (d < 0) {
r = Math.sqrt( Math.abs(d) ) / (2*a);
System.out.println("\nThe discriminant is negative. The roots of the quadratic equation are complex: r1 = " + Commons.twoDecimals(r0) + " + " + Commons.twoDecimals(r) + "i and r2 = " + Commons.twoDecimals(r0) + " - " + Commons.twoDecimals(r) + "i.\n" );
}

Finally, we only do these calculations if a > 0, since we would be dividing by zero otherwise.

if (a != 0) {...}

The discriminant of cubic polynomials can also be calculated, as well as for higher degrees, but it is not included here.