Quadratic equation

A quadratic equation is an equation of form Ax2 + Bx + C = 0, where A, B and C are given constants (with a constraint A != 0).

To solve it, a discriminant is calculated: D = B2-4AC. If D = 0, the equation has one real root x = -B/2A, otherwise it has two roots x1 = (-B+sqrt(D))/2A, x2 = (-B-sqrt(D))/2A (the roots are real or complex, depending on whether D is positive or negative).

The task is to read integer constants A, B and C entered by user, calculate the roots of the equation and output them. If A = 0, output an error message “Not a quadratic equation”. Output real roots as a single double, and complex roots a + ib as (a,b).

This class of examples shows processing of floating-point and complex numbers (if the language provides these data types). Besides, both console and graphical user interface can be used for interacting with the user.

Example for versions Borland C++ Builder 6

This example uses a template class complex<>, provided in STL. All calculations are done in complex numbers, because this allows not to worry about the sign of discriminant and representation of the roots.

Operator >> of complex is overloaded so that it can recognize several formats of the number, so the input constants are read not as integers but as complex numbers without imaginary part. This implementation allows to solve quadratic equations not only with integer coefficients but also with floating-point and even complex ones.

Operator << is also overloaded to print the number x as (x.real(),x.imag()), so to print roots without imaginary part as a single double, function print was created.

#include <iostream>
#include <complex>
#include <math>

using namespace std;

void print(int ind, complex<double> x)
{   cout << "x" << ind << " = ";
    if (fabs(x.imag()) < 1E-6)
        cout << x.real() << endl;
    else cout << x << endl;
}

void main()
{   complex<double> A, B, C, D, x1, x2;
    cout << "A = ";
    cin >> A;
    if (abs(A)<1E-3)
    {   cout << "Not a quadratic equation" << endl;
        return;
    }
    cout << "B = ";
    cin >> B;
    cout << "C = ";
    cin >> C;

    A *= 2;
    D = B*B-A*C*2.0;
    if (abs(D)<1E-3)
        cout << "x = " << (-B/A).real();
    else
    {   print(1, (-B+sqrt(D))/A);
        print(2, (-B-sqrt(D))/A);
    }
}

Example for versions Algol68g-1.18.0

A direct translation of the C++ example.

PROC print root = (INT ind, LONG COMPL x)VOID:
(   print(("x", ind, " := "));
    IF ABS(im OF x) < 1E-6 THEN
        print((re OF x, new line))
    ELSE print((x, new line))
    FI
);

main:
(   LONG COMPL a, b, c, d, x1, x2;
    print(("a := "));
    read((a));
    IF ABS a <1E-3 THEN
        print(( "Not a quadratic equation", new line));
        stop
    FI;
    print(("b := "));
    read((b));
    print(("c := "));
    read((c));

    a *:= 2;
    d := b*b-a*c*2.0;
    IF ABS d <1E-3 THEN
        print(("x := ", re OF (-b/a)))
    ELSE
        print root(1, (-b+long complex sqrt(d))/a);
        print root(2, (-b-long complex sqrt(d))/a)
    FI
)

Example for versions SpiderMonkey (Firefox 3.5)

The example is meant to be executed from the web-browser. To run the example, copy the code to a file quadratic.js and create an HTML file placed in the same directory and containing the following text:

<head>
<script type="text/javascript" src="1.js"></script>
</head>
<body>
<form name="quadratic">
    <input type="number" required="required" name="A">
    <input type="number" required="required" name="B">
    <input type="number" required="required" name="C">
    <input type="button" value="Solve" onClick="solve()">
</form>
<p id="output">
</p>
</body>

This will create a web-page with three input fields and a button. The equation will be solved once the button is pressed, and the roots will be printed beneath the inputs.

JavaScript doesn’t provide complex numbers, so the calculations are done in real numbers with separate check for discriminant sign. This implementation allows to solve quadratic equations not only with integer coefficients but also with floating-point ones.

function print(real, imag) 
{   if (Math.abs(imag)<1E-6)
        return real;
    else
        return '('+real+','+imag+')';
}

function solve() 
{   A = document.quadratic.A.value;
    if (Math.abs(A)<1E-3)
    {   document.getElementById('output').innerHTML = 'Not a quadratic equation';
        return;
    }
    B = document.quadratic.B.value;
    C = document.quadratic.C.value;
    A = 2*A;
    D = B*B-2*A*C;
    if (Math.abs(D)<1E-3)
    {   document.getElementById('output').innerHTML = 'x = '+(-B/A);
        return;
    }
    if (D>0)
        document.getElementById('output').innerHTML = 'x1 = '+print((-B+Math.sqrt(D))/A, 0)+'<br />x2 = '+print((-B-Math.sqrt(D))/A, 0);
    else
        document.getElementById('output').innerHTML = 'x1 = '+print(-B/A,Math.sqrt(-D)/A)+'<br />x2 = '+print(-B/A,-Math.sqrt(-D)/A);
}

Example for versions gcj 3.4.5, Sun Java 6

Java doesn’t provide complex numbers, so the calculations are done in real numbers with separate check for discriminant sign. This implementation allows to solve quadratic equations not only with integer coefficients but also with floating-point ones.

The coefficients are read from stream System.in, which allows only individual bytes to be read directly, so two wrapper classes InputStreamReader and BufferedReader are used to make reading more comfortable. The strings read from System.in are converted into double values using parseDouble method of class Double. In Java all input operations must be wrapped in try ... catch blocks to handle IOException — class of exceptions which are thrown by reading routines.

import java.util.*;
import java.io.*;

public class Quadratic {
    static String print(double real, double imag)
    {   if (Math.abs(imag)<1E-6)
            return ""+real;
        else 
            return "("+real+","+imag+")";
    }
    public static void main(String[] args)
    {   double A,B,C,D;
      try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("A = ");
        A = Double.parseDouble(br.readLine());
        if (Math.abs(A)<1E-3)
        {   System.out.println("Not a quadratic equation.");
            return;
        }
        System.out.print("B = ");
        B = Double.parseDouble(br.readLine());
        System.out.print("C = ");
        C = Double.parseDouble(br.readLine());
      }
      catch (Exception e) {
        System.err.println("An error occured while reading input parameters.");
        return;
      }
        A = 2*A;
        D = B*B-2*A*C;
        if (Math.abs(D)<1E-3)
        {   System.out.println("x = "+(-B/A));
            return;
        }
        if (D>0)
            System.out.println("x1 = "+print((-B+Math.sqrt(D))/A, 0)+"\nx2 = "+print((-B-Math.sqrt(D))/A, 0));
        else
            System.out.println("x1 = "+print(-B/A,Math.sqrt(-D)/A)+"\nx2 = "+print(-B/A,-Math.sqrt(-D)/A));
    }
}