65.9K
CodeProject is changing. Read more.
Home

A simple program to solve quadratic equations with

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Nov 9, 2010

CPOL
viewsIcon

6841

// Real solutions of the quadratic equation A x^2 + B x + C = 0// Returns two roots (possibly identical) in increasing order, or nonebool Quadratic(double A, double B, double C, double R[2]){ if (A == 0) { // Linear, impossible or degenerate, cannot find two roots ...

// Real solutions of the quadratic equation A x^2 + B x + C = 0
// Returns two roots (possibly identical) in increasing order, or none
bool Quadratic(double A, double B, double C, double R[2])
{
    if (A == 0)
    {
        // Linear, impossible or degenerate, cannot find two roots
        return false;
    }

    // Truly quadratic, reduce the coefficients and discuss
    A= 1 / A;
    B*= 0.5 * A;
    C*= A;
    double D= B * B - C;
    if (D < 0)
    {
        // No real root
        return false;
    }

    // Compute and sort the root(s), avoiding cancellation and division by zero
    double Q= - B + (B > 0 ? - sqrt(D) : + sqrt(D));
    R[0]= Q > 0 ? C / Q : Q;
    R[1]= Q < 0 ? C / Q : Q;

    return true;
}