Symbolic Polynomial Calculus

File: SymbolicMath.lean

This program adds, scales, differentiates, and integrates polynomials in one variable. A polynomial is a list of terms, and each term is an exponent with a coefficient. Two rules do the calculus:

math

Integration divides, so the coefficients must be fractions. Lean has an exact rational type, Rat.

The Code

  1 -- lean --run SymbolicMath.lean   (symbolic polynomial calculus)
  2 
  3 -- A polynomial is a list of (exponent, coefficient) terms with
  4 -- descending exponents, like terms combined and zeros dropped.
  5 -- 3x^2 - x + 5 = [(2, 3), (1, -1), (0, 5)]
  6 
  7 abbrev Poly := List (Nat × Rat)
  8 
  9 def normalize (terms : List (Nat × Rat)) : Poly :=
 10   let sorted := terms.mergeSort (fun a b => a.1 ≥ b.1)
 11   let merged := sorted.foldr (init := ([] : Poly)) fun (e, c) acc =>
 12     match acc with
 13     | (e', c') :: rest =>
 14       if e = e' then (e, c + c') :: rest else (e, c) :: acc
 15     | [] => [(e, c)]
 16   merged.filter (·.2 ≠ 0)
 17 
 18 -- poly [3, -1, 5] is 3x^2 - x + 5
 19 def poly (coefs : List Rat) : Poly :=
 20   normalize (coefs.reverse.zipIdx.map fun (c, e) => (e, c))
 21 
 22 def Poly.add (p q : Poly) : Poly := normalize (p ++ q)
 23 
 24 def Poly.scale (p : Poly) (k : Rat) : Poly :=
 25   normalize (p.map fun (e, c) => (e, k * c))
 26 
 27 def Poly.sub (p q : Poly) : Poly := p.add (q.scale (-1))
 28 
 29 -- none for the zero polynomial
 30 def Poly.degree (p : Poly) : Option Nat := p.head?.map (·.1)
 31 
 32 def Poly.eval (p : Poly) (x : Rat) : Rat :=
 33   p.foldl (fun acc (e, c) => acc + c * x ^ e) 0
 34 
 35 def ratToFloat (r : Rat) : Float := Float.ofInt r.num / r.den.toFloat
 36 
 37 def Poly.evalFloat (p : Poly) (x : Float) : Float :=
 38   p.foldl (fun acc (e, c) => acc + ratToFloat c * x ^ e.toFloat) 0.0
 39 
 40 -- Power rule, applied n times
 41 def Poly.deriv (p : Poly) : (n : Nat := 1) → Poly
 42   | 0 => p
 43   | n + 1 =>
 44     let d := p.filterMap fun (e, c) =>
 45       if e = 0 then none else some (e - 1, (e : Rat) * c)
 46     Poly.deriv d n
 47 
 48 -- Reverse power rule, applied n times
 49 def Poly.integ (p : Poly) : (n : Nat := 1) → Poly
 50   | 0 => p
 51   | n + 1 =>
 52     let i := p.map fun (e, c) => (e + 1, c / ((e + 1 : Nat) : Rat))
 53     Poly.integ i n
 54 
 55 inductive Bound where
 56   | num (r : Rat)
 57   | pi
 58   | e
 59 
 60 instance : OfNat Bound n := ⟨.num n⟩
 61 
 62 def Bound.toFloat : Bound → Float
 63   | .num r => ratToFloat r
 64   | .pi => 3.141592653589793
 65   | .e => Float.exp 1.0
 66 
 67 instance : ToString Bound where
 68   toString
 69     | .num r => toString r
 70     | .pi => "π"
 71     | .e => "e"
 72 
 73 def Poly.definite (p : Poly) (a b : Bound) : Float :=
 74   let f := p.integ
 75   f.evalFloat b.toFloat - f.evalFloat a.toFloat
 76 
 77 def Poly.isCriticalPoint (p : Poly) (x : Rat) : Bool :=
 78   p.deriv.eval x = 0
 79 
 80 def Poly.toString (p : Poly) (v : String := "x") : String :=
 81   if p.isEmpty then "0"
 82   else " + ".intercalate (p.map fun (e, c) =>
 83     s!"{c}{if e > 0 then v else ""}{if e > 1 then s!"^{e}" else ""}")
 84 
 85 def integralToString (p : Poly)
 86     (bounds : Option (Bound × Bound) := none) (v : String := "x") :
 87     String :=
 88   let range := match bounds with
 89     | some (a, b) => s!"[{a},{b}]"
 90     | none => ""
 91   s!"∫{range}({p.toString v}) d{v}"
 92 
 93 def fixed (x : Float) (d : Nat := 4) : String :=
 94   let n := (x.abs * (10 ^ d).toFloat).round.toUInt64.toNat
 95   let frac := toString (n % 10 ^ d)
 96   let pad := "".pushn '0' (d - frac.length)
 97   s!"{if x < 0 then "-" else ""}{n / 10 ^ d}.{pad}{frac}"
 98 
 99 def p : Poly := poly [3, -1, 5]   -- 3x^2 - x + 5
100 def q : Poly := poly [1, 2]       -- x + 2
101 
102 -- Checked when the file compiles
103 example : p.eval 2 = 15 := by native_decide
104 example : p.deriv = poly [6, -1] := by native_decide
105 example : p.integ.deriv = p := by native_decide
106 example : p.isCriticalPoint (1 / 6) = true := by native_decide
107 
108 def main : IO Unit := do
109   let s (p : Poly) := p.toString
110   IO.println s!"p          : {s p}"
111   IO.println s!"p + q      : {s (p.add q)}"
112   IO.println s!"p - q      : {s (p.sub q)}"
113   IO.println s!"2p         : {s (p.scale 2)}"
114   IO.println s!"degree, p(2): {p.degree.getD 0}, {p.eval 2}"
115   IO.println
116     s!"p', p'', p''': {s p.deriv} | {s (p.deriv 2)} | {s (p.deriv 3)}"
117   IO.println s!"∫p, ∫∫p    : {s p.integ} | {s (p.integ 2)}"
118   let i01 := integralToString p (some (0, 1))
119   let i0pi := integralToString p (some (0, .pi))
120   IO.println s!"{i01} = {fixed (p.definite 0 1)}"
121   IO.println s!"{i0pi} = {fixed (p.definite 0 .pi)}"
122   IO.println (s!"x=1/6 critical? {p.isCriticalPoint (1 / 6)}" ++
123     s!"  x=0? {p.isCriticalPoint 0}")

How It Works

  • normalize sorts the terms by exponent, adds the coefficients of terms that share an exponent, and drops zero terms. Every operation ends with normalize, so two equal polynomials are always the same list. That lets = compare them.
  • You can call the functions named Poly.add, Poly.deriv, and so on as p.add q and p.deriv.
  • deriv and integ take a count n and match on it. 0 returns the polynomial. n + 1 does one step and calls the function again with n. The := 1 in the type gives the count a default, so p.deriv is the first derivative and p.deriv 2 is the second.
  • (e : Rat) * c converts the natural number e to a rational before it multiplies.
  • Bound is an inductive type for the limits of a definite integral: a rational number, π, or e. instance : OfNat Bound n lets a number literal such as 0 stand for a Bound.
  • eval computes with Rat and gives exact answers. evalFloat computes with Float for the bounds π and e, which are not rational.
  • isCriticalPoint tests if the derivative is exactly zero. The Common Lisp version compares a float with a tolerance.
  • Lean checks the four example lines at compile time. The third states that the derivative of the integral of p is p. native_decide can check these because Rat arithmetic is exact. Float arithmetic is not: in Lean, as in most languages, 0.1 + 0.2 == 0.3 is false.

normalize has an invariant: exponents descend, exponents are unique, and no coefficient is zero. The invariant implies normalize (normalize terms) = normalize terms; chapter 21 sketches a proof of that theorem. Poly.degree reads the head exponent, so an empty list has no degree (none).

integ drops the constant of integration, so p.integ.deriv returns p and not the general antiderivative. The checked example uses that convention.

Exact arithmetic finds rational roots only: for a polynomial with an irrational critical point, isCriticalPoint returns false. A numeric version would compare with a tolerance, as the Common Lisp program does.

Multiplication

Multiplication is the natural next operation. Multiply every term of p by every term of q, add the exponents, multiply the coefficients, and normalize:

1 def Poly.mul (p q : Poly) : Poly :=
2   normalize (p.flatMap fun (e1, c1) =>
3     q.map fun (e2, c2) => (e1 + e2, c1 * c2))
4 
5 example : p.mul q = poly [3, 5, 3, 10] := by native_decide
6 example : (p.mul q).deriv = (p.deriv.mul q).add (p.mul q.deriv) := by
7   native_decide

For p = 3x^2 - x + 5 and q = x + 2, the product is 3x^3 + 5x^2 + 3x + 10. The first example checks it at compile time. The second checks the product rule: the derivative of the product equals the derivative of p times q plus p times the derivative of q.

Lean 4 Notes

Number literals have no fixed type. In poly [3, -1, 5] the literals are Rat values, because poly takes a List Rat. In p.deriv 2 the 2 is a Nat. Lean reads a literal through the type class OfNat, and any type with an instance can use digits. The line instance : OfNat Bound n := ⟨.num n⟩ adds Bound to those types. It takes the literal as a Nat, lets Lean convert it to a Rat, and wraps it in the num constructor. That is why main can write p.definite 0 1.

Exact fractions. Rat stores a numerator and a denominator in lowest terms. The fields num and den read them, and ratToFloat divides one by the other.

1 #eval (1/3 : Rat) + 1/6   -- (1 : Rat)/2

Recursion on a number. Nat is an inductive type with two forms: zero, and one more than another number. deriv matches on them as 0 and n + 1. The recursive call passes n, which is smaller, so Lean accepts the function.

A default in a function type. def Poly.deriv (p : Poly) : (n : Nat := 1) → Poly puts the count after the colon so that the lines below can match on it. The := 1 still gives it a default.

foldr. normalize uses foldr, which works from the right end of the list. Each step puts a term on the front of the result or merges it with the term already there. With foldl the result would come out reversed.

Option helpers. p.head? returns the first term or none. .map (·.1) applies a function inside the Option. .getD 0 supplies a value for none. filterMap in deriv keeps the terms for which its function returns some, which drops the constant term.

match as an expression. In integralToString, let range := match bounds with ... names the result of a match.

A statement as a Bool. isCriticalPoint returns Bool, and its body is the statement p.deriv.eval x = 0. Lean can decide equality of Rat values, so it converts the statement.

Running It

 1 $ lean --run SymbolicMath.lean
 2 p          : 3x^2 + -1x + 5
 3 p + q      : 3x^2 + 7
 4 p - q      : 3x^2 + -2x + 3
 5 2p         : 6x^2 + -2x + 10
 6 degree, p(2): 2, 15
 7 p', p'', p''': 6x + -1 | 6 | 0
 8 ∫p, ∫∫p    : 1x^3 + -1/2x^2 + 5x | 1/4x^4 + -1/6x^3 + 5/2x^2
 9 ∫[0,1](3x^2 + -1x + 5) dx = 5.5000
10 ∫[0,π](3x^2 + -1x + 5) dx = 41.7794
11 x=1/6 critical? true  x=0? false

The integral from 0 to 1 is exactly 11/2. The program prints it as a Float because definite also accepts π and e as bounds.

The printed form 3x^2 + -1x + 5 comes from Poly.toString, which joins every term with + and prints the coefficient as it is. The output is correct but reads poorly. A sign-aware printer tests the sign of each coefficient and writes - x instead of + -1x; that is a small change to Poly.toString and a useful exercise.

Using It

Add polynomial division, or a numeric version of isCriticalPoint that accepts a tolerance. Then change Poly.toString to test the sign of each coefficient and print 3x^2 - x + 5.