Solving a Quadratic Equation¶
For
$$ ax^2+bx+c=0,\qquad a\ne0, $$
the two roots are
$$ x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}. $$
Rather than entering roots separately for each example, the Egison program reads the coefficients of a polynomial, constructs its discriminant, and applies one typed symbolic solver.
Coefficients and the discriminant¶
Egison's coefficients function returns coefficients in ascending degree order. Thus the pattern $[a_0,a_1,a_2]$ recognizes $a_2x^2+a_1x+a_0$. The helper keeps the cleared-denominator discriminant $b^2-4ac$ intact and explicitly groups the denominator as $2a$.
declare symbol x, a, b, c: MathValue
def solveQuadraticCoefficientsDemo
(a : MathValue)
(b : MathValue)
(c : MathValue)
: (MathValue, MathValue) :=
let discriminant := b ^ 2 - 4 * a * c
in ( ((- b) + sqrt discriminant) / (2 * a)
, ((- b) - sqrt discriminant) / (2 * a) )
def solveQuadraticDemo
(f : MathValue)
(x : MathValue)
: (MathValue, MathValue) :=
match coefficients f x as list mathValue with
| [$a_0, $a_1, $a_2] ->
solveQuadraticCoefficientsDemo a_2 a_1 a_0
A cyclotomic example¶
The polynomial $x^2+x+1$ has discriminant $-3$. Its roots are the two primitive cube roots of unity.
solveQuadraticDemo (x ^ 2 + x + 1) x
The symbolic formula¶
Leaving $a$, $b$, and $c$ symbolic exposes the usual discriminant without any special formatting code.
solveQuadraticDemo (a * x ^ 2 + b * x + c) x
A useful rescaling¶
Writing the middle coefficient as $2b$ gives the equivalent compact form
$$ x=\frac{-b\pm\sqrt{b^2-ac}}{a}. $$
solveQuadraticDemo (a * x ^ 2 + 2 * b * x + c) x
Takeaway¶
Pattern matching and the typed helper separate the calculation into two transparent stages: read the polynomial coefficients, then form the discriminant and both signs of its square root. The displayed answers are produced from each input polynomial rather than inserted as precomputed outputs.