C++ Quadratic equation outputs: -1.#IND
Question
My code works fine with: (1, -2, -8), It gives me the error above when I input a=1 b=0 c=1,
Here is my code:
double x=0,a=0,b=0,c=0,d=0;
complexType solu1;
complexType solu2;
cout << "\n\nEnter values of quadratic a,b,c:";
cin >> a >> b >> c;
double solution1 = (-1.0 * b) + (sqrt((b * b) - (4 * a * c)));
solu1 = solution1 / (2*a);
cout << setprecision(5) << solu1;
double solution2 = (-b) - (sqrt((b*b) - (4 * a * c)));
solu2 = solution2 / (2*a);
cout << setw(5) << setprecision(5) << solu2;
How can I remedy this?
Solution
You are trying to find a real solution to x^2 + 1 = 0
, which only has imaginary solutions.
If you want to solve all quadratic equations, then you need to check whether the discriminant is positive to determine whether the solutions are real or complex:
double d = b*b - 4*a*c;
if (d >= 0) {
double sol1 = (-b + sqrt(d))/(2*a);
double sol2 = (-b - sqrt(d))/(2*a);
std::cout << sol1 << ", " << sol2 << '\n';
} else {
double real = -b/(2*a);
double imag = sqrt(-d)/(2*a);
std::cout << real << " +/- " << imag << "i\n";
}
You could do something neater with std::complex
if you want.
OTHER TIPS
sqrt((b*b) - (4 * a * c))
for your inputs is sqrt(-4)
. According to http://www.cplusplus.com/reference/clibrary/cmath/sqrt/, If the argument is negative, a domain error occurs, setting the global variable errno to the value EDOM.
I don't see a definition for what it returns in that case. Either way, that's wrong.
I see that you have complexType
in your code. If that's a typedef of std::complex<T>
, then the code is easily fixable.
complexType top = b*b - 4*a*c;
solu1 = (-b + sqrt(top)) / (2*a);
solu2 = (-b - sqrt(top)) / (2*a);
Since std::sqrt
has an overload for std::complex<T>
.