Part 7. SymPy: symbolic once, numeric many times#
SymPy excels at exact computation: it expands, simplifies, differentiates, sums, and proves
identities. Each of its operations, however, builds and traverses an expression tree made of Python
objects. In Lecture 3 we built such a system ourselves (MiniCAS), so we know how much work hides
behind a single substitution. That is why SymPy is very slow when we use it as a calculator in a
loop. The rule of this part is: we do the symbolic computation once and turn its result into a
fast numerical function, which we then call many times. The second rule: when we know what we
want, we choose specialized tools instead of general ones (simplify, Rational in a loop). The
examples come from Lectures 3 and 5.
import inspect
import math
import random
from fractions import Fraction
import numpy as np
import sympy as sp
from sympy.core.cache import clear_cache
import minicas
srodowisko("numpy", "sympy")
Pomiary: Apple M4, macOS 26.6.2, Python 3.12.11, numpy 2.5.3, sympy 1.14.0
Values of an expression at many points#
In Lecture 3 (§3.4) we evaluated the expression \(\sin(x+1)+\cos(x+1)\) at a thousand random points
in two ways: with the MiniCAS interpreter, which traverses the expression tree at every point, and
with a virtual machine, for which the MiniCAS compiler translates the tree once. Let us add SymPy
to the comparison: substitution with subs followed by evalf, the value evalf(subs=...), and
the function sp.lambdify, which turns an expression into an ordinary Python function. The
functions that use SymPy clear SymPy’s cache before each call (see part 1),
because otherwise we would be measuring the retrieval of stored results.
x = sp.symbols("x")
w = sp.sin(x + 1) + sp.cos(x + 1)
w_minicas = minicas.parse("sin(x+1) + cos(x+1)")
program = minicas.compile_expr(w_minicas)
f_math = sp.lambdify(x, w, "math")
f_numpy = sp.lambdify(x, w, "numpy")
random.seed(20261025) # te same punkty co na wykładzie 3
punkty = [random.uniform(-10, 10) for _ in range(1000)]
punkty_tablica = np.array(punkty)
def sympy_subs(ts):
clear_cache()
return [float(w.subs(x, t).evalf()) for t in ts]
def sympy_evalf(ts):
clear_cache()
return [float(w.evalf(subs={x: t})) for t in ts]
czasy_wartosci = porownaj({
"SymPy: subs i evalf": lambda: sympy_subs(punkty),
"SymPy: evalf(subs=...)": lambda: sympy_evalf(punkty),
"MiniCAS: interpreter drzewa":
lambda: [minicas.numeric(w_minicas, {"x": t}) for t in punkty],
"MiniCAS: maszyna wirtualna":
lambda: [program.run({"x": t}, exact=False) for t in punkty],
"lambdify(..., 'math')": lambda: [f_math(t) for t in punkty],
"lambdify(..., 'numpy')": lambda: f_numpy(punkty_tablica),
}, zgodne=lambda a, b: np.allclose(np.asarray(a, dtype=float),
np.asarray(b, dtype=float),
rtol=1e-12, atol=1e-12))
wykres_czasow(czasy_wartosci, "sin(x+1) + cos(x+1) w 1000 punktów")
wariant czas przyspieszenie
SymPy: subs i evalf 177 ms 1.0×
SymPy: evalf(subs=...) 22.7 ms 7.8×
MiniCAS: interpreter drzewa 5.01 ms 35×
MiniCAS: maszyna wirtualna 1.28 ms 138×
lambdify(..., 'math') 64.5 µs 2753×
lambdify(..., 'numpy') 7.35 µs 24157×
The difference between the first and the last row is four orders of magnitude. Substitution in
SymPy builds a new tree at every point, simplifies it, and only then computes the value. The
MiniCAS interpreter is faster, because it only traverses the tree, without building a new one. The
MiniCAS virtual machine traverses the tree once, at compile time. The function lambdify goes one
step further: it writes Python source code and compiles it with the built-in compiler. This can be
seen in the code it generated:
print(inspect.getsource(f_math))
def _lambdifygenerated(x):
return sin(x + 1) + cos(x + 1)
It is the same idea as the compiler from Lecture 3: we turn the expression tree into a program
once. Here, however, the program is a Python function executed by the CPython interpreter, and in
the "numpy" version the loop over the points runs in C. SymPy can also translate expressions into
code in C and other languages (sp.ccode, the sympy.utilities.codegen module) or, for high
precision, into functions of the mpmath library (lambdify(..., "mpmath")).
Let us return to the profiler example from part 1. The trapezoidal rule with values computed by
subs spent almost all of its time in SymPy. After replacing subs with lambdify:
f_calka = sp.exp(-x**2)
g_math = sp.lambdify(x, f_calka, "math")
g_numpy = sp.lambdify(x, f_calka, "numpy")
def trapezy_subs(n):
clear_cache()
h = sp.Rational(1, n)
ys = [float(f_calka.subs(x, k * h)) for k in range(n + 1)]
return (sum(ys) - (ys[0] + ys[-1]) / 2) / n
def trapezy_lambdify(n):
ys = [g_math(k / n) for k in range(n + 1)]
return (sum(ys) - (ys[0] + ys[-1]) / 2) / n
def trapezy_numpy(n):
ys = g_numpy(np.linspace(0, 1, n + 1))
return (ys.sum() - (ys[0] + ys[-1]) / 2) / n
czasy_trapezy = porownaj({"subs (część 1)": trapezy_subs,
"lambdify, math": trapezy_lambdify,
"lambdify, numpy": trapezy_numpy}, 200,
zgodne=lambda a, b: abs(a - b) < 1e-14)
wariant czas przyspieszenie
subs (część 1) 20.9 ms 1.0×
lambdify, math 13.4 µs 1558×
lambdify, numpy 3.90 µs 5347×
The same computation is now thousands of times faster. We announced this in part 1 after reading the profile: it pays to speed up the part of the program where the time really goes.
Polynomials: Poly instead of expressions#
A SymPy expression is a general tree: a sum of products of powers. For polynomials, SymPy has a
separate representation, the class Poly. It stores only the exponents and the coefficients, and
it multiplies polynomials with algorithms for polynomials over a specific ring, here over
\(\mathbb Z\). This is the same choice that MiniCAS made in Lecture 3 (§3.3): a polynomial is a set
of monomials, that is, of exponent tuples with coefficients, not a tree. Let us multiply two
polynomials of degree \(8\) in three variables:
y, z = sp.symbols("y z")
e1, e2 = (x + y + z + 1)**8, (x - y + 2*z - 1)**8
P1, P2 = sp.Poly(e1, x, y, z), sp.Poly(e2, x, y, z)
def iloczyn_expand():
clear_cache()
return sp.expand(e1 * e2)
def iloczyn_poly():
clear_cache()
return P1 * P2
def iloczyn_poly_z_zamiana():
clear_cache()
return (sp.Poly(e1, x, y, z) * sp.Poly(e2, x, y, z)).as_expr()
wynik = iloczyn_expand()
assert sp.Poly(wynik, x, y, z) == iloczyn_poly()
print("jednomianów w iloczynie:", len(iloczyn_poly().terms()))
czasy_poly = porownaj({
"expand(e1 * e2)": iloczyn_expand,
"Poly * Poly": iloczyn_poly,
"Poly z zamianą tam i z powrotem": iloczyn_poly_z_zamiana},
zgodne=lambda a, b: True)
jednomianów w iloczynie: 897
wariant czas przyspieszenie
expand(e1 * e2) 443 ms 1.0×
Poly * Poly 3.99 ms 111×
Poly z zamianą tam i z powrotem 48.4 ms 9.1×
We checked that the results agree before the measurement (assert). Multiplication in Poly is
tens to hundreds of times faster, and even with the conversion of the expression to Poly and
back, it beats expand many times over. When a computation consists of many operations on
polynomials (division with remainder, GCD, Gröbner bases), we convert the expression to Poly
once, at the beginning.
simplify or a specific operation#
The function sp.simplify tries many simplification strategies and picks the shortest result. It
is convenient but slow, and the form of the result is hard to predict. When we know what we want,
we call a specific operation: cancel (reducing a fraction), factor, expand, together,
trigsimp.
r = (x**6 - 1) / (x**2 - 1)
def przez_simplify():
clear_cache()
return sp.simplify(r)
def przez_cancel():
clear_cache()
return sp.cancel(r)
def przez_factor():
clear_cache()
return sp.factor(r)
for f in (przez_simplify, przez_cancel, przez_factor):
print(f"{f.__name__:15} {f()}")
czasy_upraszczanie = porownaj({"simplify": przez_simplify,
"cancel": przez_cancel,
"factor": przez_factor},
zgodne=lambda a, b: sp.cancel(a - b) == 0)
przez_simplify x**4 + x**2 + 1
przez_cancel x**4 + x**2 + 1
przez_factor (x**2 - x + 1)*(x**2 + x + 1)
wariant czas przyspieszenie
simplify 3.45 ms 1.0×
cancel 768 µs 4.5×
factor 527 µs 6.5×
Even more important than time is the certainty of the result. In Lecture 5 (§5.3) we proved
formulas for sums of powers by checking that \(S(n)-S(n-1)-n^p\) is the zero polynomial. The
function udowodnij did this with sp.expand(...) == 0, not with sp.simplify(...) == 0. For
polynomials, expand is a decision procedure: a polynomial is zero if and only if nothing is
left after expanding and collecting like terms. The function simplify is a heuristic. When it
does not return zero, we do not know whether the expression is nonzero or simplify merely failed
to find a way. For expressions with elementary functions, one cannot do better. Richardson’s
theorem (deep dive) says that already for expressions with the
sine and the absolute value, there is no algorithm that decides whether an expression is
identically zero.
n, k = sp.symbols("n k", integer=True, positive=True)
S = sp.expand(sp.summation(k**10, (k, 1, n)))
tozsamosc = S - S.subs(n, n - 1) - n**10
def zero_przez_expand():
clear_cache()
return sp.expand(tozsamosc) == 0
def zero_przez_simplify():
clear_cache()
return sp.simplify(tozsamosc) == 0
czasy_zero = porownaj({"simplify(...) == 0": zero_przez_simplify,
"expand(...) == 0": zero_przez_expand})
wariant czas przyspieszenie
simplify(...) == 0 10.8 ms 1.0×
expand(...) == 0 2.70 ms 4.0×
Here both functions answer correctly, but expand does so faster and with a guarantee.
Rational numbers: Rational, Fraction, and a better algorithm#
SymPy numbers (sp.Rational, sp.Integer) are expression objects. Every operation goes through
SymPy’s machinery: type checking, ordering of arguments, the cache. In a loop with thousands of
operations on numbers, fractions.Fraction works better. Better still is to change the algorithm.
Let us compute the harmonic number \(H_{2000}=1+\tfrac12+\dots+\tfrac1{2000}\) exactly. Summing the
fractions one after another reduces the result after every addition, and reduction requires the
GCD of ever longer numbers. Binary splitting divides the summation range into halves, sums each
half recursively as a pair of integers (numerator, denominator) without reducing, and reduces only
once, at the end:
where \(P_1/Q_1\) and \(P_2/Q_2\) are the sums over the two halves. At every step, the numbers being multiplied have similar lengths, and it is on such multiplications that fast big-integer arithmetic gains the most.
def h_rational(n):
clear_cache()
return sum(sp.Rational(1, k) for k in range(1, n + 1))
def h_fraction(n):
return sum(Fraction(1, k) for k in range(1, n + 1))
def dzielenie_binarne(a, b):
"""Suma 1/k dla a <= k < b jako para (licznik, mianownik)."""
if b - a == 1:
return 1, a
s = (a + b) // 2
p1, q1 = dzielenie_binarne(a, s)
p2, q2 = dzielenie_binarne(s, b)
return p1 * q2 + p2 * q1, q1 * q2
def h_binarnie(n):
return Fraction(*dzielenie_binarne(1, n + 1)) # Fraction skraca raz
def h_harmonic_od_zera(n):
sp.harmonic.harmonic_cache.clear() # tego clear_cache nie czyści
clear_cache()
return sp.harmonic(n)
def jako_fraction(q):
return Fraction(int(sp.numer(q)), int(sp.denom(q)))
czasy_h = porownaj({"suma sp.Rational": h_rational,
"suma Fraction": h_fraction,
"dzielenie binarne": h_binarnie,
"sp.harmonic od zera": h_harmonic_od_zera,
"sp.harmonic z pamięcią": sp.harmonic}, 2000,
zgodne=lambda a, b: jako_fraction(a) == jako_fraction(b))
H = h_binarnie(2000)
print(f"H_2000: licznik ma {len(str(H.numerator))} cyfr,",
f"mianownik {len(str(H.denominator))}")
wariant czas przyspieszenie
suma sp.Rational 15.6 ms 1.0×
suma Fraction 2.22 ms 7.0×
dzielenie binarne 671 µs 23×
sp.harmonic od zera 18.6 ms 0.84×
sp.harmonic z pamięcią 103 ns 151738×
H_2000: licznik ma 867 cyfr, mianownik 866
The sum of Fraction numbers is several times faster than the sum of sp.Rational numbers, and
binary splitting is faster still. The advantage of binary splitting grows with \(n\) (exercise 3).
The same technique is used to compute constants such as \(\pi\) or \(e\) to millions of digits
(B. Haible, T. Papanikolaou, Fast multiprecision evaluation of series of rational numbers, 1998).
The last two rows are a cautionary tale about measurement. Computed from scratch, sp.harmonic
adds up sp.Rational numbers one after another, so it is as slow as our sum. The second time,
however, it takes a fraction of a microsecond. SymPy remembers all the computed \(H_k\) in its own
dictionary sp.harmonic.harmonic_cache, which clear_cache does not clear. Had we not noticed
this, we would have declared sp.harmonic the fastest algorithm, while measuring nothing but a
dictionary lookup.
Summary#
We do the symbolic computation once and turn the result into a numerical function with
sp.lambdify. This speeds up the evaluation thousands of times:subsin a loop is the slowest way to compute values.lambdifyis a compiler like the one from Lecture 3: it turns the expression tree into Python code, and with the"numpy"module it computes on whole arrays.For polynomials, we use
Poly, not general expressions.Instead of
simplify, we choose a specific operation (cancel,factor,expand). For polynomial identities,expand(...) == 0is faster and gives a certain answer.In loops over rational numbers, we use
Fraction, and a better algorithm (binary splitting) gives even more.When timing SymPy, we clear SymPy’s cache (
clear_cache) and remember that some functions have caches of their own (sp.harmonic).
Exercises#
★ Plot the interpolating polynomial from Lecture 5 at \(10^4\) points, computing the values with
subsand withlambdify. Measure both running times.★ Compare
sp.diffwithexpandand withsimplifyfor the derivative of order \(10\) of the function \(e^{x}\sin x\). Which form of the result is shorter?★★ Compare the
Fractionsum with binary splitting for \(H_n\), \(n=10^3, 10^4, 10^5\). How does the ratio of the running times grow?★★ Time
sp.factorfor \(x^n-1\) and \(n=60, 120, 240\). Explain the number of factors (cyclotomic polynomials) and compare it with the number of divisors of \(n\).★★ Use
sp.lambdify(x, w, "mpmath")to compute \(\sin(x+1)+\cos(x+1)\) to \(50\) digits at the point \(x=10^{20}\). Compare with the"math"version. Which one is correct, and why?