I am reposting this because I accidentally deleted my first post.
The solution is presented as a pair of complex roots, unless
a == 0
, in which case the equation is linear and returns a single complex(real) root.
If
a == 0
and
b == 0
, the function fails.
Given a complex type, replace the real and imaginary type double arrays with a single type complex array .
Likewise, if there is a preferred method for establishing floating point equality with
0
, replace the boolean
aIsZero
and
bIsZero
flags as necesary.
bool Quadratic(double a, double b, double c, CArray<double,>& real, CArray<double,>& imaginary)
{
bool bReturn = true;
real.RemoveAll();
imaginary.RemoveAll();
bool aIsZero = !((a > 0) || (a < 0));
bool bIsZero = !((b > 0) || (b < 0));
if(aIsZero)
{
if(bIsZero)
{
real.SetSize(0);
imaginary.SetSize(0);
bReturn = false;
}
else
{
real.SetSize(1);
imaginary.SetSize(1);
real[0] = -c/b;
imaginary[0] = 0.0;
}
}
else
{
real.SetSize(2);
imaginary.SetSize(2);
double dDiscriminant = b*b - 4.0 * a * c;
if(dDiscriminant < 0)
{
real[0] = -b / 2.0 / a;
real[1] = real[0];
imaginary[0] = sqrt(-dDiscriminant) / 2.0 / a;
imaginary[1] = -imaginary[0];
}
else
{
real[0] = (-b + sqrt(dDiscriminant)) / 2.0 / a;
real[1] = (-b - sqrt(dDiscriminant)) / 2.0 / a;
imaginary[0] = 0.0;
imaginary[1] = 0.0;
}
}
return bReturn;
}