I have constructed an extremely simple, yet fully-functioning and quite helpful, WinForms C# application that solves for the real roots of a quadratic equation.
Here is my current programming logic:
string noDivideByZero = "Enter an a value that isn't 0";
txtSolution1.Text = noDivideByZero;
txtSolution2.Text = noDivideByZero;
decimal aValue = nmcA.Value;
decimal bValue = nmcB.Value;
decimal cValue = nmcC.Value;
decimal solution1, solution2;
string solution1String, solution2String;
//Quadratic Formula: x = (-b +- sqrt(b^2 - 4ac)) / 2a
//Calculate discriminant
decimal insideSquareRoot = (bValue * bValue) - 4 * aValue * cValue;
if (insideSquareRoot < 0)
{
//No real solution
solution1String = "No real solutions!";
solution2String = "No real solutions!";
txtSolution1.Text = solution1String;
txtSolution2.Text = solution2String;
}
else if (insideSquareRoot == 0)
{
//One real solution
decimal sqrtOneSolution = (decimal)Math.Sqrt((double)insideSquareRoot);
solution1 = (-bValue + sqrtOneSolution) / (2 * aValue);
solution2String = "No real solution!";
txtSolution1.Text = solution1.ToString();
txtSolution2.Text = solution2String;
}
else if (insideSquareRoot > 0)
{
//Two real solutions
decimal sqrtTwoSolutions = (decimal)Math.Sqrt((double)insideSquareRoot);
solution1 = (-bValue + sqrtTwoSolutions) / (2 * aValue);
solution2 = (-bValue - sqrtTwoSolutions) / (2 * aValue);
txtSolution1.Text = solution1.ToString();
txtSolution2.Text = solution2.ToString();
}
txtSolution1
and txtSolution2
are the text boxes which aren't allowed to receive input, but output the results of the calculation
nmcA
, nmcB
and nmcC
are NumericUpDown controls which are used for a, b and c value input by the end user
OK, so, I was hoping to take it a step further, and possibly solve for imaginary values as well. Considering I have the conditionals already set up, I would need to account for imaginary values only when the discriminant is equal to 0
or less than 0
.
However, I can't think of a good way to approach this. The complex solutions occur when one attempts to take the square root of a negative number, leading to the i
s appearing everywhere. i = sqroot(-1)
and i^2 = -1
.
Does anyone know how to approach this problem, or if it is just not worth the time?
EDIT
With a little more Googling, I have found that it is possible with C# 4.0 (or .NET 4.0 I'm not sure which) there is built-in complex number support in System.Numerics.Complex
. I'm checking this out now.