1.3. How does a computer algebra system work?#

A computer algebra system (CAS) is a program that transforms mathematical expressions exactly: it operates on symbols, integers and rationals, radicals, polynomials, and functions rather than on their approximations. The first such systems appeared in the 1960s (among them FORMAC and Schoonschip, and, toward the end of the decade, Reduce and MIT’s Macsyma); today the best known are Mathematica (1988), Maple, Magma (1993), PARI/GP, Maxima, and, in the Python world, SymPy and SageMath.

In this section we look “under the hood” of SymPy and ask which mathematical problems the designer of such a system has to solve. We will see, in turn:

  • how a CAS represents expressions, and which simplifications it performs on its own and which only on request;

  • how it computes exactly, and what a canonical form is;

  • why the zero problem is undecidable in general;

  • how it deals with branches of multivalued functions and with assumptions about variables;

  • where expression swell comes from, and which algorithms work inside.

Most examples use the symbols \(x\), \(y\), \(z\), which we create at the start:

import sympy as sp
x, y, z = sp.symbols('x y z')

1.3.1. An expression is a tree#

A CAS does not store the string (x+1)**2*sin(x) but an expression tree: operations (Add, Mul, Pow, functions) at the internal nodes, symbols and numbers at the leaves. The function srepr shows this structure directly:

e = (x + 1)**2 * sp.sin(x)
sp.srepr(e)
"Mul(Pow(Add(Symbol('x'), Integer(1)), Integer(2)), sin(Symbol('x')))"

Every node has a head (func), i.e., the kind of operation, and arguments (args), which are themselves expressions built in the same way. For every expression that is not a leaf (i.e., has nonempty args), we have e.func(*e.args) == e: the expression can be rebuilt from its head and arguments. Leaves, i.e., symbols and numbers, have empty args and store their content differently; for example, x.func(*x.args) fails with a TypeError.

e.func, e.args
(sympy.core.mul.Mul, ((x + 1)**2, sin(x)))

This recursive structure lets us traverse the whole tree with a short recursive function. A leaf (an expression without arguments) is printed directly; at an internal node we print the name of the operation and descend into the arguments, increasing the indentation:

def show(expr, indent=0):
    label = expr.func.__name__ if expr.args else repr(expr)
    print("    " * indent + label)
    for arg in expr.args:
        show(arg, indent + 1)

show(e)
Mul
    Pow
        Add
            1
            x
        2
    sin
        x

Note that in the Add node the number 1 comes before x, although we typed x + 1. SymPy stores the arguments of commutative operations in a fixed order, independent of the order in which they were typed — thanks to this, expressions that are equal “up to commutativity” have identical trees.

Subtraction and division are not separate operations: \(a-b\) is Add(a, Mul(-1, b)), and \(a/b\) is Mul(a, Pow(b, -1)). Fewer kinds of nodes mean simpler algorithms.

sp.srepr(x - y), sp.srepr(x / y)
("Add(Symbol('x'), Mul(Integer(-1), Symbol('y')))",
 "Mul(Symbol('x'), Pow(Symbol('y'), Integer(-1)))")

Applet

Expression tree — type in any expression and look at its tree, its srepr form, and its canonical form.

1.3.2. Automatic and explicit simplification#

SymPy already performs a few cheap simplifications when an expression is created; they are valid for all (or almost all) values of the variables: it collects like terms, “flattens” nested sums and products, sorts the arguments into a fixed order, and evaluates operations on numbers.

x + x, x * x, 2 * 3 * x, (y + x).args
(2*x, x**2, 6*x, (x, y))

The result (x, y) of (y + x).args confirms that the arguments are sorted. The word “almost” is important: SymPy also automatically replaces x/x with 1, although the quotient is undefined for \(x = 0\). We will return to such simplifications “outside an exceptional set” when we discuss reducing fractions. Automatic simplification can be switched off with the argument evaluate=False — the tree then stays exactly as we built it, i.e., a sum of two identical terms:

sp.Add(x, x, evaluate=False)          # this is the tree without automatic simplification
\[\displaystyle x + x\]

Everything that is more expensive or requires a decision is explicit — we call it ourselves:

Function

What it does

expand

multiplies out products

factor

factors into irreducible factors (over \(\Q\))

cancel, together, apart

rational functions: cancellation, common denominator, partial fractions

trigsimp, powsimp, logcombine

simplification of trigonometric expressions, powers, logarithms

simplify

a heuristic: tries many transformations and picks the “simplest” result

Let us compare three of these functions on the rational function \(w = \frac{x^2-1}{x^2+2x+1}\):

w = (x**2 - 1) / (x**2 + 2*x + 1)
sp.factor(w), sp.cancel(w), sp.apart(w)
((x - 1)/(x + 1), (x - 1)/(x + 1), 1 - 2/(x + 1))

The functions factor and cancel gave the same result, \(\frac{x-1}{x+1}\): the numerator and the denominator have the common factor \(x+1\), because \(x^2 - 1 = (x-1)(x+1)\) and \(x^2 + 2x + 1 = (x+1)^2\). The function apart returns the partial fraction decomposition, \(1 - \frac{2}{x+1}\). So we have three forms of the same rational function (the original one, the reduced one, and the partial fraction decomposition), each “simplest” in a different sense — and that is precisely why the choice of transformation is up to us.

1.3.3. Exact arithmetic#

Numbers in SymPy are usually exact: integers of any size, rationals, radicals and other algebraic numbers, constants such as \(\pi\). An approximation is produced only on request (evalf, N), and with a precision of your choice. First, a few exact computations:

sp.Rational(1, 3) + sp.Rational(1, 6), sp.sqrt(8), sp.sqrt(2)**2
(1/2, 2*sqrt(2), 2)

The numbers stay exact: \(\sqrt{8}\) was automatically brought to the form \(2\sqrt{2}\) (the square factor was taken out from under the radical), and \((\sqrt{2})^2\) is exactly \(2\). And this is what approximations of \(\sqrt{2}\) with \(50\) and of \(\pi\) with \(30\) significant digits look like:

sp.N(sp.sqrt(2), 50), sp.N(sp.pi, 30)
(1.4142135623730950488016887242096980785696718753769,
 3.14159265358979323846264338328)

The number of digits is not decoration here: N(expr, n) returns an approximation with \(n\) significant digits, and SymPy (using the mpmath library) chooses the precision of the intermediate computations so that in typical cases all of these digits are correct.

Beware of “contamination” by floating-point numbers: 0.5*x is no longer the same as x/2.

0.5 * x, x / 2, sp.Rational(1, 2) * x == x / 2, 0.5 * x == x / 2
(0.5*x, x/2, True, False)

The number 0.5 in an expression becomes a Float object, so 0.5*x and x/2 are two different trees: the product of a floating-point number and a symbol, and the product of the rational number \(\tfrac12\) and a symbol. The comparison == is structural, which is why it returns False, although mathematically the two expressions are equal. In SymPy we therefore write fractions as sp.Rational(1, 2) or x/2, not as decimal numbers.

1.3.4. Canonical forms and the equality problem#

How can we check whether two expressions are equal? In SymPy, the == operator compares trees, not mathematical values:

(x + 1)**2 == x**2 + 2*x + 1
False

The result False is not a bug: the trees on the two sides are different (a power of a sum, and a sum of three terms), and == performs no transformations.

For polynomials there is a canonical form: after multiplying out all products and ordering the monomials, every polynomial has exactly one representation. Mathematical equality then reduces to comparing strings (trees):

sp.expand((x + 1)**2) == x**2 + 2*x + 1, sp.expand((x + 1)**2 - (x**2 + 2*x + 1))
(True, 0)

Similarly for rational functions: the representation \(p/q\) with \(\gcd(p, q) = 1\) and a monic denominator is canonical — but computing it requires an algorithm for the GCD of polynomials. This is the first example showing that even “simple” simplification rests on nontrivial algebra.

Definition

Let \(E\) be a class of expressions in which \(f \equiv g\) denotes mathematical equality (e.g., equality of functions). A computable function \(c\colon E \to E\) is a canonical form for the class \(E\) if for all \(f, g \in E\): (1) \(c(f) \equiv f\) and (2) \(f \equiv g \iff c(f) = c(g)\), where \(=\) denotes identity of representations (trees). A normal form satisfies (1) and the weaker condition (2’): \(f \equiv 0 \iff c(f) = 0\).

For polynomials, the canonical form is the expanded form, with the monomials ordered in a fixed way. For rational functions, it is the quotient \(p/q\) of coprime polynomials with a monic denominator (one with leading coefficient \(1\)). A normal form suffices for deciding equality in a class closed under subtraction, because then \(f \equiv g \iff f - g \equiv 0 \iff c(f-g) = 0\); a canonical form gives more — a single common representation for all mathematically equal expressions.

1.3.5. The zero problem and Richardson’s theorem#

The most important question for a CAS is: is a given expression identically equal to zero? For polynomials and rational functions, the canonical form provides the answer. For broader classes — unfortunately, not always:

Theorem (D. Richardson, 1968)

Consider expressions built from rational numbers, \(\pi\), \(\ln 2\), the variable \(x\), the operations \(+\) and \(\cdot\), composition, and the functions \(\sin\), \(\exp\), and \(|\cdot|\). There is no algorithm that decides, for every such expression \(E(x)\), whether \(E(x) = 0\) for all real \(x\).

It follows that no simplification algorithm can, for every expression in this class, terminate and return \(0\) exactly when the expression is identically zero. Every simplify function must therefore fail on some expressions: it may fail to recognize zero, give a wrong answer, or never finish the computation.

Full proof

A proof sketch and a complete step-by-step proof (with definitions, illustrations in Python, review questions, and problems) are in the chapter Richardson’s theorem: why a computer cannot recognize every zero (in the Deep dives part of the book). Applet: one variable suffices.

In practice, simplify is a collection of heuristics, which are often very effective. Let us check two trigonometric identities:

sp.simplify(sp.sin(x)**2 + sp.cos(x)**2), sp.simplify(sp.cos(x)**4 - sp.sin(x)**4 - sp.cos(2*x))
(1, 0)

SymPy recognized both identities: \(\sin^2 x + \cos^2 x = 1\) and \(\cos^4 x - \sin^4 x = (\cos^2 x - \sin^2 x)(\cos^2 x + \sin^2 x) = \cos 2x\). This does not contradict Richardson’s theorem, which only says that no method works for all expressions.

The equals method tries to decide equality in various ways — including by computing numerical values at random points. It usually answers True when the difference of the two sides could be simplified to zero; the random values serve mainly to detect a difference (the answer False). Since they are computed approximately, such an answer is not a proof, only strong evidence.

((x + 1)**2).equals(x**2 + 2*x + 1)
True

For this polynomial identity the answer is certain: the difference of the two sides simplifies to zero, that is, to the canonical form of the zero polynomial. In harder cases, equals may return None, which means that the equality could not be decided — an honest “I don’t know.”

1.3.6. Branches and assumptions#

Many “obvious” transformations are valid only under additional assumptions. A symbol created by sp.symbols('x') stands for an arbitrary complex number, and in a CAS the square root and the logarithm are the principal branches of multivalued functions: \(\log w = \ln|w| + i\operatorname{Arg} w\), where \(\operatorname{Arg} w \in (-\pi, \pi]\), and \(\sqrt{w} = e^{(\log w)/2}\) for \(w \neq 0\). That is why a CAS must not perform such transformations silently:

sp.sqrt(x**2), sp.simplify(sp.sqrt(x**2))       # nothing happens — rightly so!
(sqrt(x**2), sqrt(x**2))

For \(x = -3\) we have \(\sqrt{x^2} = 3 \neq x\), and for \(x = -i\) we have \(\sqrt{x^2} = \sqrt{-1} = i \neq x\). Only information about the domain makes it possible to simplify this expression:

xr = sp.symbols('x', real=True)
xp = sp.symbols('x', positive=True)
sp.sqrt(xr**2), sp.sqrt(xp**2)
(Abs(x), x)

The assumption real=True gives \(\sqrt{x^2} = |x|\), and positive=True gives simply \(x\). Assumptions are part of the symbol, so for SymPy xr and xp are two different variables, although both are printed as x.

Similarly, \(\log(ab) = \log a + \log b\) does not hold for all complex numbers (e.g., for \(a = b = -1\) the left-hand side is \(\log 1 = 0\), and the right-hand side is \(2\log(-1) = 2\pi i\)):

a, b = sp.symbols('a b')
ap, bp = sp.symbols('a b', positive=True)
sp.expand_log(sp.log(a*b)), sp.expand_log(sp.log(ap*bp)), sp.expand_log(sp.log(a*b), force=True)
(log(a*b), log(a) + log(b), log(a) + log(b))

Without assumptions, SymPy does not expand the logarithm. For positive \(a\) and \(b\) the formula is true, so expand_log applies it. The option force=True forces the transformation despite the lack of assumptions — the responsibility for its correctness then passes to us.

Reducing fractions also changes the domain: \(\frac{x^2-1}{x-1}\) is undefined at \(x=1\), whereas the result of cancel is defined there.

sp.cancel((x**2 - 1) / (x - 1))
\[\displaystyle x + 1\]

The two functions are equal everywhere except at the point \(x = 1\), but they are not the same function: the first one is not defined at that point. Computer algebra systems accept such simplifications “outside an exceptional set”; it is up to us to remember the exceptions when the domain matters.

1.3.7. Expression swell#

The canonical form can be huge. There are \(\binom{d+2}{2}\) monomials of degree \(d\) in three variables (that is the number of solutions of the equation \(i + j + k = d\) in nonnegative integers), so the expansion of \((x+y+z)^{20}\) has \(\binom{22}{2} = 231\) monomials — all of them with nonzero coefficients:

len(sp.expand((x + y + z)**20).args)
231

More dangerous still is coefficient growth during a computation, even when the result is small. A classic example is given by D. Knuth (The Art of Computer Programming, vol. 2, §4.6.1). Let us run the Euclidean algorithm over \(\Q\) for two polynomials with small integer coefficients and, for each successive remainder, print its degree and its leading coefficient:

u = sp.Poly(x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5, x, domain='QQ')
v = sp.Poly(3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21, x, domain='QQ')
p, q = u, v
while not q.is_zero:
    p, q = q, p.rem(q)
    if not q.is_zero:
        print(q.degree(), q.all_coeffs()[0])
4 -5/9
2 -117/25
1 233150/19773
0 -1288744821/543589225

The successive remainders have ever larger numerators and denominators. The last nonzero remainder is the nonzero constant \(-\tfrac{1288744821}{543589225}\), so \(u\) and \(v\) are coprime, and their monic GCD is simply \(1\). That is why systems used in practice compute GCDs differently: with subresultant sequences, with modular methods (computing modulo many primes combined with the Chinese remainder theorem), or with heuristics. By default, SymPy uses the heuristic algorithm GCDHEU.

1.3.8. Algorithms under the hood#

The table collects the most important algorithms on which computer algebra systems rely, together with the SymPy or Sage functions that use them:

Task

Algorithm

In SymPy / Sage

GCD of integers and polynomials

Euclidean algorithm, extended Euclidean algorithm, modular methods

gcd, gcdex

multiplication of large integers and polynomials

Karatsuba, FFT

internally (GMP/FLINT)

factorization of polynomials over \(\Z\)

factorization modulo \(p\) (Berlekamp, Cantor–Zassenhaus), Hensel lifting, factor recombination (Zassenhaus, van Hoeij)

factor

systems of polynomial equations

Gröbner bases (Buchberger, F4/F5)

groebner

indefinite integrals in terms of elementary functions

the Risch algorithm (+ heuristics)

integrate, risch_integrate

symbolic sums

Faulhaber’s formula, Gosper’s algorithm (in other systems also Zeilberger’s algorithm)

summation, gosper_sum

lattices, integer relations

LLL

Sage: LLL()

For example, for a polynomial summand the function summation uses (as can be seen in the SymPy source code) Faulhaber’s formula, expressed via Bernoulli polynomials. Gosper’s algorithm (1978) covers a wider class: for a hypergeometric term \(t_k\), i.e., one for which \(t_{k+1}/t_k\) is a rational function of \(k\), it decides whether the indefinite sum of the terms \(t_k\) is also a hypergeometric term, and if so, finds it:

from sympy.concrete.gosper import gosper_sum
k, n = sp.symbols('k n', integer=True, nonnegative=True)
sp.factor(sp.summation(k, (k, 1, n))), gosper_sum(k, (k, 0, n)), sp.factor(sp.summation(k**3, (k, 1, n)))
(n*(n + 1)/2, n*(n + 1)/2, n**2*(n + 1)**2/4)

We obtained the well-known formulas \(\sum_{k=1}^{n} k = \frac{n(n+1)}{2}\) and \(\sum_{k=1}^{n} k^3 = \frac{n^2(n+1)^2}{4}\). The second sum is the square of the first — this is Nicomachus’s identity.

1.3.9. Challenges in designing a CAS — a summary#

  1. Representation: trees, or graphs in which repeated subtrees are stored only once; dense polynomials (a list of all coefficients) or sparse ones (a list of the nonzero monomials).

  2. Canonical forms: they exist for polynomials and rational functions; for elementary expressions the zero problem is undecidable in general (Richardson).

  3. Semantics of simplification: what does “simpler” mean? Who decides on the branch of a root or a logarithm?

  4. Assumptions and domains: \(\sqrt{x^2}\), \(\log(ab)\), reducing fractions.

  5. Efficiency: expression and coefficient swell, the need for modular algorithms.

  6. Correctness: CASs are large programs, and hence they contain bugs. A well-known example: A. J. Durán, M. Pérez, J. L. Varona, The Misfortunes of a Trio of Mathematicians Using Computer Algebra Systems. Can We Trust in Them?, Notices of the AMS 61(10), 2014 — incorrectly computed determinants of matrices with large integer entries.

The practical conclusion: we verify the results of a CAS — by substituting values, with another system, and, when the stakes are high, with a formal proof. That is what the next section is about.

1.3.10. SymPy vs. SageMath#

Finally, let us compare the two systems we use in this course:

SymPy

SageMath

implementation

pure Python

Python + many libraries in C/C++ (PARI, FLINT, Singular, GAP, …) and in Lisp (Maxima)

installation

pip install sympy

a large distribution (conda-forge, installer, cloud)

speed

sufficient for learning and medium-sized computations

much higher in heavy algebra and number theory

use in this course

the main tool in the labs

comparisons, larger computations, algebraic structures

In the labs we work mainly in SymPy, and we turn to Sage for larger computations and where algebraic structures are needed.