Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Go to top

A simple program to solve quadratic equations with

, 15 Nov 2010
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Michael Waters
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 --
| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 15 Nov 2010
Article Copyright 2010 by Michael Waters
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid