Click here to Skip to main content
15,895,011 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.
0.00/5 (No votes)
15 Nov 2010CPOL 5.8K   2  
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...
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)	//	a == 0, so linear, not quadratic
	{
		if(bIsZero)	//	undefined behavior, fail function
		{
			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)	//	imaginary roots
		{
			real[0] = -b / 2.0 / a;
			real[1] = real[0];

			imaginary[0] = sqrt(-dDiscriminant) / 2.0 / a;
			imaginary[1] = -imaginary[0];
		}
		else	//	real roots, duplicate roots if dDiscriminant == 0
		{
			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;
}

License

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


Written By
Engineer
United States United States
BS Aerospace Engineering 1993, University of Virginia
ME Aerospace Engineering 1995, University of Virginia

Comments and Discussions

 
-- There are no messages in this forum --