Computer algebra systems such as Mathematica, Maple and SymPy have long been part of how we do mathematics. Whether we are deriving an equation, working out an integral or simplifying a particularly unpleasant expression, it is often much easier to ask a computer to do the calculation. But when formalizing mathematics in Lean, we still need to prove that the resulting expression is correct. This can take considerably more effort than finding the answer itself. SymLean grew out of our interest in making these two processes work together. We wanted something that feels like a conventional computer algebra system but produces Lean theorems that we can use directly in our proofs.
The library covers symbolic algebra, differentiation, integration, series expansions, limits,
equation solving, special functions and certified numerical computation. We can run a calculation
interactively with #cas, or inside an existing Lean proof with the cas and cega tactics. The
nice part is that the algorithms we use to find an answer don't have to be trusted. They can be
heuristic, and we can even delegate computations to external computer algebra systems.
Dashed arrows are proposals, which nobody has to trust. SymLean turns them into certificates and proofs with Mathlib and FloatLib, and Lean's kernel checks the result.
Documentation · Getting started · Why SymLean · Trust assumptions
From a checkout of this repository, fetch the Mathlib cache and build SymLean:
lake exe cache get
lake buildUse the Lean version in lean-toolchain (v4.36.0, with Mathlib v4.36.0).
Dependency versions are pinned in lake-manifest.json.
In your own Lake project, add SymLean with require:
require SymLean from git "https://github.com/lean-dojo/SymLean.git" @ "main"Then run lake update SymLean and lake exe cache get, and start a file with import CAS. A library
that reads files into proofs with include_str or json_data% should add SymLean's facet
SymLean.embeddedInputs to its needs, so that Lake rebuilds a module when such a file changes (see
the library guide).
If you have used Mathematica, Maple or SymPy, #cas will feel familiar: you give it a mode and an
expression, and it answers. The difference is that every answer comes back as a theorem that Lean
has checked. Here is a short session, with the answers SymLean prints:
import CAS
#cas [factor] (2*x^3 - 3*x^2 + 1) -- (x - 1)^2*(2*x + 1)
#cas [derive x] (x ^ 2 * sin x) -- x*(2*sin(x) + x*cos(x))
#cas [integrate x] (atan x) -- x*atan(x) - 1/2*log(1 + x^2)
#cas [integrate x in [0, 1]] (x * exp x) -- 1
#cas [limit x → 0] (sin x / x) -- 1
#cas [series x 0 7] (sin x) -- x - 1/6*x^3 + 1/120*x^5 - 1/5040*x^7 + o(x^7)
#cas [sum k 1 n] (k^2) -- n*(n + 1)*(2*n + 1)/6
#cas [solve x] (x ^ 2 = 1) -- x = 1 ∨ x = -1
#cas [roots x] (x ^ 5 - x - 1 = 0) -- 1.16730397826141868425, the only real root
#cas [dsolve y x] (y'' + 3*y' + 2*y = 0) -- y(x) = c₁*exp(-x) + c₂*exp(-(2*x))
#cas [eigenvalues] !![2, 0, 0; 0, 3, 4; 0, 4, 9] -- [1, 2, 11]
#cas (zeta 4) -- pi^4/90
#cas [nintegrate x in [0, 1]] (exp (-x^2)) -- 0.746824 ± 10^-6
#cas [simplify] ((x ^ 4 - 1) / (x ^ 2 - 1)) -- x^2 + 1, when x^2 - 1 ≠ 0Each line also prints the theorem behind its answer, with the conditions under which it holds:
the simplification needs
In a proof, the tactics do the same work on your own goals:
theorem integral_x_exp : ∫ x in (0 : ℝ)..1, x * Real.exp x = 1 := by
cas
example (x : ℝ) (hx : x ≠ 0) : x / x = 1 := by
cas
example (x : ℝ) (h0 : 0 ≤ x) (h1 : x ≤ 1) : x * (1 - x) ≤ 1 / 4 := by
cegacas proves the definite integral in Mathlib's own terms. The second goal needs hx, because
division in Lean is total: hx the
tactic fails and names the missing hypothesis x ≠ 0. cega proves the bound cas? and cega? suggest a tactic call to keep.
Every mode has a page with examples in the documentation.
-
Simplifying.
simplifyandfullSimplifyrewrite an expression and prove that the result equals it under the conditions they print: cancelling$d$ adds$d \neq 0$ .together,cancelandaparthandle fractions. See the algebra guide. -
Expanding and factoring.
expand,factor,collectandtrigExpandprove identities for all real values.factorfinds rational roots and perfect powers, and doesn't claim that what's left is irreducible. Seefactor. -
Polynomials. Coefficients, degrees, division with remainder, gcds with their Bézout cofactors
and interpolation, all about Mathlib's
ℚ[X]. See the polynomials guide. -
Gröbner bases.
groebnerproves that its basis spans the same ideal and, by Buchberger's criterion, that it is a Gröbner basis.memberproves ideal membership with explicit cofactors. Seegroebner.
-
Equations.
solveandrootsprove that no real solution is missing, and irrational roots come in intervals that hold exactly one root each.reduceproves where a polynomial inequality holds, andfindRootencloses a root of any equation. See the guide. -
Matrices.
det,inverse,matrixRank,rowReduce,linearSolveandnullSpace, each a theorem about Mathlib's definitions.linearSolvedescribes every solution. See the guide. -
Eigenvalues. Exact eigenvalues with their multiplicities and a proof that there are no others,
eigenvectors, characteristic polynomials, and
positiveDefinitefrom an exact$L D L^T$ factorization. See the guide.
-
Derivatives and extrema.
deriveandgradproveHasDerivAtandHasGradientAttheorems, with the conditions they need as hypotheses.minimizeandmaximizefind the extrema of a polynomial, with a theorem that no value beats them. See the guide. -
Integrals.
integratefinds an antiderivative, checks it by differentiation and proves the definite integral, also over infinite intervals. It doesn't factor a general denominator, so1 / (x ^ 3 - 1)is refused. Seeintegrate. -
Series and limits. Taylor and Laurent series with a little-o remainder, and limits at a point,
from either side, or at
$\pm\infty$ , as Mathlib'sTendsto. See the guide.
-
Sums. Closed forms of finite sums and products, proved by induction, including terms
$c^k R(k)$ by Gosper's algorithm, and infinite sums such as$\sum 1/k^2 = \pi^2/6$ with aHasSumtheorem. See the guide. -
Recurrences.
rsolvesolves linear recurrences with constant coefficients and proves that every solution has the printed form. In a proof,casgets the closed form from the recurrence and the initial values in your hypotheses. Seersolve. -
Number theory. Divisors, totients, modular powers and inverses, the Chinese remainder theorem,
Jacobi symbols, digits, continued fractions, binomials and Fibonacci numbers, each about Mathlib's
definitions.
#casdoesn't factor integers or test primality. See the guide.
-
Differential equations.
dsolvesolves linear equations and proves that the printed family is exactly the set of solutions, or with initial values the only one.ndsolveproves that a solution exists and is unique, and encloses it. See the guide. -
Transforms. Laplace and inverse Laplace transforms, Fourier transforms of Gaussians, and
Fourier coefficients as exact functions of
$n$ . -
Special functions. Exact values of
gamma,zetaand the Bernoulli numbers; the Chebyshev, Hermite, Legendre, Laguerre, Jacobi and Gegenbauer polynomials in monomials; and enclosures oferfandBesselJ. See the guide.
- Digits and enclosures.
N dgives the firstddigits of a real number with a theorem that each one is right,enclosebounds an expression on a box, andnintegrategives an integral to 6 places with a proved error. See the numerics guide. - The
cegatactic. In a proof,cegaproves numerical bounds with a certificate that the kernel checks, such asReal.exp 1 ≤ 2.72or∫ x in (0 : ℝ)..1, Real.exp (-x ^ 2) ≤ 3 / 4. It computes with exact rationals, or with IEEE floats through FloatLib if you ask. Seecega. - Big certificates.
CAS.Certchecks a condition over tables and meshes of any size, in one module or spread over many. See the guide.
cas. State the goal in Mathlib's terms and writecas: identities, derivatives, integrals, limits, sums, determinants, root counts and bounds. A condition it needs comes from your hypotheses, and a missing one is reported, never added.cas?andcega?tell you the call to keep. See the tactics guide.
- Other computer algebra systems. With the optional
CASOracle, SymPy, SageMath, Maxima, Giac, Singular, PARI/GP, FLINT and Gappa propose answers, and SymLean proves each one or refuses it. See the oracle page. - Your own functions.
@[cas_deriv]teachescasa derivative and@[cas_route]adds a route. A registry only chooses which theorem to apply, so it adds no assumption. See the library guide.
Computer algebra systems sometimes give wrong answers. One reason is that an answer only holds under
a condition they don't print. Richard Fateman's review of Mathematica (J. Symbolic Computation 13(5),
1992) reports that Integrate[1/x^2, {x, -1, 1}]
gave integrate(sqrt(2 - x)*sqrt(1/(2 - x)), (x, 0, 1)), although the integrand
is
SymLean gives none of these wrong answers. Interestingly, on Fateman's integral our own search
proposes #cas [integrate x in [-1, 1]] (1 / x ^ 2) refuses:
error: `cas` did not prove the value -2 of the integral: it could not prove that the conditions of the primitive -(1/x) hold on the interval (x ≠ 0). The endpoint calculation needs a primitive valid throughout the interval.
On SymPy's integrand our search finds no antiderivative and says so. For the matrix from Sage's
report, SymLean returns row operations
A theorem from SymLean relies on:
- its statement: the one you wrote, or the one the
#casreport prints; - the Mathlib definitions it mentions, such as
Real.arctan, and in a few answers SymLean's own short definitions, such asCAS.erf; - Lean's kernel, with the three standard axioms
propext,Classical.choiceandQuot.sound.
A report prints its statement through Lean's pretty printer, which writes a cast as ↑n without its
target type, so two different statements can look the same. When that matters, I'd write the
statement as an example in your own file and prove it there. set_option cas.suggest true offers
that example, ready to paste.
One option, off by default, trusts more: with cega.nativeCertificates, cega [fast] and the
certificate commands check large finite certificates with compiled code, and #print axioms then
shows the native axioms involved. TRUST.md lists everything a proof trusts with the reason
for each item, and the trust tutorial
goes through both profiles.
Independent kernels (lake check --paranoid) accept SymLean proofs; TRUST.md
says what to expect for large certificates.
- A refusal proves nothing. A search can miss an answer that exists, and SymLean does not compute everything Mathematica can.
- An answer is correct, but complete only when the theorem says so, as with
roots.findRootproves one root and its uniqueness near the printed value. - A certified bound on a residual is not a bound on an error. It becomes one only through a stability theorem that your own proof supplies.
- Every answer pays for a proof. Checking large finite tables in the kernel can be slow. The certificate guide explains how to split the work across modules or opt into compiled evaluation.
We'd love help with SymLean, and CONTRIBUTING.md says where to start. Please
follow Mathlib's conventions and keep every proof complete. lake exe cache get and then
lake build check every proof, the examples included, with warnings as errors. The library
guide lists the test scripts,
scripts/dups.sh and the site build to run on a change.
Letting an untrusted search propose and the prover check is an old idea: Harrison and Théry combined HOL with Maple this way (J. Automated Reasoning 21, 1998). The closest project in Lean is Hex, the Lean FRO's really nice library of verified computational algebra, which proves factorization, determinants and primality in Lean. On Lean 4.35, SymLean called Hex for Berlekamp–Zassenhaus factoring, Bareiss determinants and primality certificates. That route comes back as soon as Hex is released for Lean 4.36, and we're in touch with its developers. We build on earlier work in HOL Light, Isabelle, Coq and Rocq, and Lean, and Why SymLean cites it.
Here's what we use, and where it comes from :)
-
Hermite reduction, for the rational part of
integrate: Hermite, Nouv. Ann. Math. 1872; Bronstein, 2005. -
Gosper's algorithm, for hypergeometric sums in
sum: Gosper, PNAS 1978. -
C-finite recurrences, for the general solution of
rsolve: Stanley, Enumerative Combinatorics 1 (2012). -
Linear differential equations with constant coefficients, for
dsolve: Teschl, Ordinary Differential Equations and Dynamical Systems (2012). -
Buchberger's algorithm, for
groebnerand polynomial systems insolve: Buchberger, Aequationes Math. 1970. - Sturm sequences, for counting and isolating real roots: Sturm, Mém. Savans Étrangers 1835; Basu, Pollack and Roy, 2006.
-
The Faddeev–LeVerrier recursion, for
characteristicPolynomial: Hou, SIAM Review 1998. -
$L D L^T$ factorization, the certificate ofpositiveDefinite: Golub and Van Loan, Matrix Computations (2013). -
Interval arithmetic with subdivision and the monotonicity test, for
cega: Moore, Kearfott and Cloud (2009); Hansen, Numer. Math. 1980. - The Krawczyk operator, for enclosures of roots and of zeros of systems: Krawczyk, Computing 1969; Rump, Acta Numerica 2010.
- Taylor models, for validated approximations of functions: Makino and Berz, Int. J. Pure Appl. Math. 2003.
- Ball arithmetic and Kronecker substitution, which keep long computations cheap in the kernel: van der Hoeven 2010; Harvey, J. Symb. Comput. 2009.
-
Quadrature with Peano-kernel remainders, Simpson's rule in
nintegrateand Gauss rules in the library: Gauss 1816; Peano 1913. The Gauss rules for any weight on any interval, Laguerre, Hermite and Jacobi among them, follow Gautschi, Orthogonal Polynomials (2004). -
Validated initial value problems, for
ndsolve: Nedialkov, Jackson and Corliss, Appl. Math. Comput. 1999. - Root enclosures start from Kerner's iteration, Numer. Math. 1966, and Mahler's separation bound, Michigan Math. J. 1964.
- Sums of squares with rational coefficients, for the inequality certificates of the oracles: Parrilo, 2003; Peyrl and Parrilo, 2008.
- Proof by reflection, for the normalizers that the kernel runs: Boutin, TACS 1997.
SymLean is written at Caltech by Robert Joseph George, Changhe Yang, Peicong Song, Thomas Y. Hou and Anima Anandkumar. Everything here is built on Mathlib (The mathlib Community, "The Lean Mathematical Library", CPP 2020, https://doi.org/10.1145/3372885.3373824). The certified numerics use FloatLib by Robert Joseph George, Will Adkisson and Anima Anandkumar. Many thanks to taterowney and the DSLean contributors for DSLean, which is under CC BY 4.0.
SymLean is released under the Apache License 2.0; see LICENSE.