Click here to Skip to main content
15,885,829 members
Articles / Programming Languages / C++
Alternative
Tip/Trick

A simple program to solve quadratic equations with

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
9 Nov 2010CPOL 6.7K   2  
// 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 ...
C#
// 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;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO VISION fOr VISION
Belgium Belgium
I fell into applied algorithmics at the age of 16 or so. This eventually brought me to develop machine vision software as a professional. This is Dreamland for algorithm lovers.

Comments and Discussions

 
-- There are no messages in this forum --