Java Snippets

Hamburger icon

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:

ax2+bx +c



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:


There are three cases:

Quadratic eq discriminant

  1. If Δ = 0, the polynomial has one real double root:
  2. x1=x2=-b2a

    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. -b+Δ2a and -b-Δ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. -b2a+-Δ2a and -b2a--Δ2a

    which can also be written as:

    -b2a+Δ2ai and -b2a-Δ2ai

    since i=-1 and -Δ=-1Δ=iΔ. So we take r0 and calculate r as Δ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.

View Quadratic Root's repo