0

How to use algebraic formula to find the roots of the quadratic equation in C ?

28th Jan 2021, 7:40 AM
Avatar
2 Answers
+ 1
Ok, I sow I got down-voted with my short answer, so here is the long: Using the well known formula we all learn in school is not a great idea, at least not for both the solutions. Infact is widely known that floating point numbers and subtraction don't go well togheter, expecially if both members are close to each other. To avoid this we take from the two formulas: -b / 2a + sqrt(b^2-4ac) / 2a -b / 2a - sqrt(b^2-4ac) / 2a The one where '-b' and 'sqrt(...)' have the same sign. We know that sqrt is always positive, so it all depends on the sign of b So, assuming b!=0, we can clearly see that our first solution is X1 = -b/2a - sgn(b) sqrt(b^2-4ac)/2a As for our second solution we could use the less-known formula: -2c/b +- 2c/sqrt(b^2-4ac) Or use the fact that c=a*X1*X2 So X2 = c/(a*X1) If b==0 than we know: X1 = + sqrt(c/a) X2 = - sqrt(c/a) As for the case where b^2-4ac < 0 we can compute that for the Complex solutions or just signal that there are no Real solutions
28th Jan 2021, 8:43 AM
Angelo
Angelo - avatar
0
short answer: Assuming b!=0 check if b*b-4ac >= 0 X1=(-b-sgn(b)*sqrt(b*b-4*a*c))/(2*a) X2=c/(a*X1) sqrt() is in the math.h library sgn() is (t>0)-(t<0)
28th Jan 2021, 8:15 AM
Angelo
Angelo - avatar