13,596,314 members
Alternative Tip/Trick
alternative version

Stats

4.2K views
2 bookmarked
Posted 9 Nov 2010
Licenced CPOL

A simple program to solve quadratic equations with

, 9 Nov 2010
// 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;
}```

Share

 CEO VISION fOr VISION 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.