I am trying to write a function in C++ that solves for X using the quadratic equation. This is what I have written initially, which seems to work as long as there are no complex numbers for an answer:
float solution1 = (float)(-1.0 * b) + (sqrt((b * b) - (4 * a * c)));
solution1 = solution1 / (2*a);
cout << "Solution 1: " << solution1 << endl;
float solution2 = (float)(-b) - (sqrt((b*b) - (4 * a * c)));
solution2 = solution2 / (2*a);
cout << "Solution 2: " << solution2;
If, for example, I use the equation: x^2 - x - 6, I get the solution 3, -2 correctly.
My question is how would I account for complex numbers....for example, given the equation:
x^2 + 2x + 5
Solving by hand, I would get -1 + 2i, -1 - 2i.
Well, I guess two question, can I write the above better and also make it account for the complex number?
Thanks for any help!
Nicking the idea from Blindy:
Something like this would work:
That way you get the results in a similar way for both real and complex results (the real results just have the imaginary part set to 0). Would look even prettier with boost!
edit: fixed for the delta thing and added a check for degenerate cases like a=0. Sleepless night ftl!
I tried the program without using 'math.h' header and also tried different logic...but my program can answer only those quadratic equations which have coefficient of 'x square' as one ..... and where coefficient of 'x' can be expressed as an addition of two numbers which are factors of constant term. eg. x square +8x+16; x square +7x+12; etc. here 8=4+4 & 16=4*4; here coefficient of x can be expressed as an addition of two numbers which are factors of constant term 16... I myself is not fully satisfied with it but tried something different, without using the formula for solving quadratic equation. code is;
An important note to all of this. The solutions shown in these responses and in the original question are not robust.
The well known solution (-b +- sqrt(b^2 - 4ac)) / 2a is known to be non-robust in computation when ac is very small compered to b^2, because one is subtracting two very similar values. It is better to use the lesser known solution 2c / (-b -+ sqrt(b^2 -4ac)) for the other root.
A robust solution can be calculated as:
The use of sign(b) ensures that we are not subtracting two similar values.
For the OP, modify this for complex numbers as shown by other posters.
You more or less have it, just check to see if the part that's inside the square root is negative and then keep track of that separately in your reductions.
You could basically just use
std::complex<float>
instead offloat
to get support for complex numbers.