SolveQuadratic Function |
Unit
QESBPCSMath
Declaration
Function SolveQuadratic(const A, B, C: Extended; out X1, X2: Extended): Byte;
Description
The function returns the number of roots found, and X1 & X2 are the values.
Parameters |
A | Coefficient of X^2 in the Quadratic Equation. |
B | Coefficient of X in the Quadratic Equation. |
C | Constant in the Quadratic Equation. |
X1 | First Root of the Quadratic Equation. |
X2 | Second Root of the Quadratic Equation. |
Returns
0 then there are no roots, X1 = X2 = 0. 1 then there is only one root, X1 = X2. 2 then there are two distinct roots X1 <> X2.
Category
Arithmetic Routines for FloatsImplementation
function SolveQuadratic (const A, B, C: Extended; out X1, X2: Extended): Byte; var Det, Q: Extended; begin Det := Sqr (B) - 4 * A * C; if FloatIsNegative (Det) then begin X1 := 0; X2 := 0; Result := 0; end else if FloatIsZero (A) then begin if FloatIsZero (B) then raise EMathError.Create (rsNotDefinedForValue); X1 := -C / B; X2 := X1; Result := 1; end else if FloatIsZero (det) then begin X1 := -0.5 * B / A; X2 := X1; Result := 1; end else begin Det := Sqrt (Det); {: Rather than the "traditional" algebraic solution, we use a method that improved accuracy, especially when either A or C or both are much closer to zero than B, then the discriminant is nearly equal to B and one of the calculations will involve the subtraction of two nearly equal quantities. Thanks to Rory Daulton for this improvement. } if B < 0 then Q := -0.5 * (B - Det) else Q := -0.5 * (B + Det); X1 := Q / A; X2 := C / Q; Result := 2; end; End; |
|