I just came around and decided to try some Ada.
The downside is that the syntax and function strays quite away from C++.
So I had to like cram various stuff to get this thing to work.
My question is if there are some better way to do this calculation that what I have done here
IF(B < 0.0) THEN
B := ABS(B);
X1 := (B / 2.0) + Sqrt( (B / 2.0) ** 2.0 + ABS(C));
X2 := (B / 2.0) - Sqrt( (B / 2.0) ** 2.0 + ABS(C));
ELSE
X1 := -(B / 2.0) + Sqrt( (B / 2.0) ** 2.0 - C);
X2 := -(B / 2.0) - Sqrt( (B / 2.0) ** 2.0 - C);
END IF;
I had some problem with negative numbers, that’s why I did a IF statement and used ABS() to turn those into positive. But the weird thing is that it works perfectly for the other case, which is strange…
Solving quadratic equations is not as simple as most people think.
The standard formula for solving
a x^2 + b x + c = 0isbut when
4 a c << b^2, computingx1involves subtracting close numbers, and makes you lose accuracy, so you use the following insteadwhich yields a better x1, but whose x2 has the same problem as x1 had above.
The correct way to compute the roots is therefore
and use
x1 = q / aandx2 = c / q, which I find very efficient. If you want to handle the case whendeltais negative, or complex coefficients, then you must use complex arithmetic (which is quite tricky to get right too).Edit: With Ada code: