Part 6. Ready-made algorithms: SciPy and linear algebra#
In part 5 we moved our own algorithms into NumPy. The next rung of laziness is to use algorithms that someone has already written and refined. NumPy and SciPy rely on libraries that have been developed for decades: LAPACK and BLAS (linear algebra), QUADPACK (integration), and many others. They are faster than the simple implementations from the lectures, because they take care of the CPU cache and of vector instructions. They are often also more accurate, because they choose pivots, estimate the error, and recognize special cases. We write the implementations from Lectures 5 and 6 in order to understand the methods. In actual computations we use libraries, unless we need a result that is exact or verifiable. Then we return to rational numbers, but it will turn out that even here it is possible to be lazy.
import math
from fractions import Fraction
import numpy as np
import scipy.integrate
import scipy.optimize
import scipy.special
import sympy as sp
from scipy.interpolate import BarycentricInterpolator
srodowisko("numpy", "scipy", "sympy")
Pomiary: Apple M4, macOS 26.6.2, Python 3.12.11, numpy 2.5.3, scipy 1.18.1,
sympy 1.14.0
Gaussian elimination vs. numpy.linalg.solve#
In Lecture 6 (§6.1) we wrote Gaussian elimination
with partial pivoting. The same function works on float and Fraction numbers.
Let us compare it on float numbers with the function np.linalg.solve. That function calls
a routine from the LAPACK library: LU decomposition with partial pivoting, performed in blocks so
that most of the work is matrix multiplication.
def eliminacja(A, b):
"""Eliminacja Gaussa z częściowym wyborem elementu głównego (wykład 6)."""
n = len(A)
M = [list(w) + [bi] for w, bi in zip(A, b)]
for k in range(n):
p = max(range(k, n), key=lambda i: abs(M[i][k]))
M[k], M[p] = M[p], M[k]
for i in range(k + 1, n):
m = M[i][k] / M[k][k]
M[i] = [a - m * c for a, c in zip(M[i], M[k])]
x = [0] * n
for i in reversed(range(n)):
s = M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))
x[i] = s / M[i][i]
return x
los = np.random.default_rng(2026)
def uklad(n):
"""Losowy układ z całkowitymi współczynnikami od -9 do 9."""
return los.integers(-9, 10, (n, n)), los.integers(-9, 10, n)
rozmiary = [25, 50, 100, 200]
czasy_python, czasy_lapack = [], []
for n in rozmiary:
A, b = uklad(n)
Af, bf = A.astype(float), b.astype(float)
Al, bl = Af.tolist(), bf.tolist()
assert np.allclose(eliminacja(Al, bl), np.linalg.solve(Af, bf))
czasy_python.append(zmierz(eliminacja, Al, bl))
czasy_lapack.append(zmierz(np.linalg.solve, Af, bf))
t_py, t_la = czasy_python[-1], czasy_lapack[-1]
print(f"n = {n:3}: Python {czas(t_py):>9} LAPACK {czas(t_la):>9}",
f" przyspieszenie {krotnosc(t_py / t_la):>6}")
wykres_skalowania(rozmiary, {"eliminacja Gaussa w Pythonie": czasy_python,
"np.linalg.solve (LAPACK)": czasy_lapack},
"Rozwiązanie układu n × n")
n = 25: Python 203 µs LAPACK 5.11 µs przyspieszenie 40×
n = 50: Python 1.34 ms LAPACK 14.6 µs przyspieszenie 92×
n = 100: Python 10.6 ms LAPACK 43.3 µs przyspieszenie 245×
n = 200: Python 85.4 ms LAPACK 139 µs przyspieszenie 614×
The time of the elimination in Python grows like \(n^3\): a system twice as large means a computation about eight times longer, and a slope of \(3\) on the log-log plot. LAPACK performs the same number of operations, but its advantage grows with \(n\) and for \(n=200\) exceeds a factor of a hundred. For small systems, LAPACK’s time is largely the fixed cost of the call. For large ones, what counts is that the routine performs the operations in blocks that fit in the CPU cache.
Matrix multiplication: three loops and @#
Matrix multiplication is the most thoroughly optimized operation in numerical computing. The
dgemm routine from the BLAS library, called by the @ operator, has versions written separately
for many processors. In the instructor’s study, single-threaded BLAS turned out to be many times
faster even than carefully written C code running on four cores. Let us compare three loops in
Python, a neater version with zip and sum, and the @ operator.
def mnozenie_petle(A, B):
n, m, p = len(A), len(B), len(B[0])
C = [[0.0] * p for _ in range(n)]
for i in range(n):
for j in range(p):
s = 0.0
for k in range(m):
s += A[i][k] * B[k][j]
C[i][j] = s
return C
def mnozenie_zip(A, B):
kolumny = list(zip(*B))
return [[sum(a * b for a, b in zip(wiersz, k)) for k in kolumny]
for wiersz in A]
A, B = los.random((120, 120)), los.random((120, 120))
Al, Bl = A.tolist(), B.tolist()
czasy_mnozenie = porownaj({"trzy pętle": lambda: mnozenie_petle(Al, Bl),
"zip i sum": lambda: mnozenie_zip(Al, Bl),
"A @ B (BLAS)": lambda: A @ B},
zgodne=lambda X, Y: np.allclose(X, Y))
wariant czas przyspieszenie
trzy pętle 35.1 ms 1.0×
zip i sum 39.8 ms 0.88×
A @ B (BLAS) 10.8 µs 3268×
The @ operator is more than a thousand times faster than the loops. The neater notation with
zip and sum does not help: it changes the way the code is written, but not the fact that each
of the \(120^3\) multiplications is executed by the interpreter.
Exact computation: rational numbers and checking#
In Lecture 6 we also solved systems exactly, with Fraction numbers, because an approximation in
float numbers can be worthless, as for the Hilbert matrix. Exact computation is slower: the
numerators and denominators grow, and multiplying long numbers is costly. Let us compare our
elimination on Fraction numbers with the LUsolve method from SymPy. Let us also measure how
much it costs to check a given solution, that is, to multiply out \(Ax\) and compare it with
\(b\).
from sympy.core.cache import clear_cache
def sprawdz(A, x, b):
"""Kontroler: czy A x = b dokładnie?"""
return all(sum(a * xi for a, xi in zip(w, x)) == bi for w, bi in zip(A, b))
def lu_sympy(As, bs):
clear_cache() # bez pamięci podręcznej (zob. część 1)
return As.LUsolve(bs)
wiersze = []
for n in (20, 40):
A, b = uklad(n)
Aq = [[Fraction(int(a)) for a in w] for w in A]
bq = [Fraction(int(v)) for v in b]
x = eliminacja(Aq, bq)
assert sprawdz(Aq, x, bq)
t_rozw, t_spr = zmierz(eliminacja, Aq, bq), zmierz(sprawdz, Aq, x, bq)
As, bs = sp.Matrix(A.tolist()), sp.Matrix(b.tolist())
assert list(lu_sympy(As, bs)) == x
t_sympy = zmierz(lu_sympy, As, bs)
cyfry = max(len(str(v.denominator)) for v in x)
wiersze.append((n, t_rozw, t_sympy, t_spr, cyfry))
print(f"{'n':>3} {'Fraction':>10} {'SymPy LUsolve':>14} {'sprawdzenie':>12}"
f" {'rozw./spr.':>11} {'cyfry mianownika':>17}")
for n, t_rozw, t_sympy, t_spr, cyfry in wiersze:
print(f"{n:3} {czas(t_rozw):>10} {czas(t_sympy):>14} {czas(t_spr):>12}"
f" {krotnosc(t_rozw / t_spr):>11} {cyfry:>17}")
n Fraction SymPy LUsolve sprawdzenie rozw./spr. cyfry mianownika
20 2.97 ms 19.8 ms 349 µs 8.5× 23
40 27.7 ms 149 ms 1.88 ms 15× 52
Two conclusions. A general-purpose symbolic library is not always the fastest: LUsolve in SymPy
is slower than a dozen or so lines on Fraction numbers, among other reasons because in SymPy
every number is an expression object. The second conclusion is more important. Checking
a solution is many times cheaper than finding it, and the advantage grows with \(n\): solving
requires on the order of \(n^3\) operations, checking on the order of \(n^2\). This is the same
asymmetry on which the whole course rests: a result may be found by a fast and complicated program
(a library, a heuristic, a language model), and trust comes from a simple checker.
Roots of equations: bisection vs. brentq#
Bisection from Lecture 5 (§5.1) needs about
\(\log_2\bigl((b-a)/\varepsilon\bigr)\) function values. Brent’s method (scipy.optimize.brentq)
also maintains an interval with a sign change, so it is just as reliable. As long as it can,
however, it takes interpolation steps, which converge much faster. When the function is cheap,
this does not matter. When each of its values is expensive, the number of calls determines the
time. We look for \(t\) such that \(\int_0^t e^{-x^2}\,dx=\tfrac12\). Each value of the function is
an integral computed numerically.
wywolania = 0
def f(t):
global wywolania
wywolania += 1
return scipy.integrate.quad(lambda x: math.exp(-x * x), 0, t)[0] - 0.5
def bisekcja(f, a, b, eps):
fa = f(a)
while b - a > eps:
m = (a + b) / 2
fm = f(m)
if (fa < 0) == (fm < 0):
a, fa = m, fm
else:
b = m
return (a + b) / 2
dokladnie = scipy.special.erfinv(1 / math.sqrt(math.pi)) # erf(t) = 1/√π
METODY = {"bisekcja": lambda: bisekcja(f, 0.0, 2.0, 1e-12),
"brentq": lambda: scipy.optimize.brentq(f, 0.0, 2.0, xtol=1e-12)}
for nazwa, metoda in METODY.items():
wywolania = 0
t = metoda()
print(f"{nazwa:9} t = {t:.15f} błąd {abs(t - dokladnie):.1e}",
f" wartości f: {wywolania}")
czasy_pierwiastek = porownaj(METODY, zgodne=lambda a, b: abs(a - b) < 1e-11)
bisekcja t = 0.551039427609339 błąd 3.1e-13 wartości f: 42
brentq t = 0.551039427609020 błąd 6.4e-15 wartości f: 9
wariant czas przyspieszenie
bisekcja 86.4 µs 1.0×
brentq 21.6 µs 4.0×
Brent’s method needs several times fewer function values and is therefore several times faster.
We compare the result with a formula: \(\int_0^t e^{-x^2}dx=\tfrac{\sqrt\pi}{2}\operatorname{erf}(t)\),
so \(t=\operatorname{erf}^{-1}(1/\sqrt\pi)\), and the inverse of \(\operatorname{erf}\) is available in
scipy.special.
Interpolation: Lagrange’s formula vs. the barycentric form#
In Lecture 5 (§5.3) we computed the interpolating polynomial for
Runge’s function with the BarycentricInterpolator class from SciPy. Lagrange’s formula applied
directly, \(p(t)=\sum_i y_i\prod_{j\ne i}\frac{t-x_j}{x_i-x_j}\), requires on the order of \(n^2\)
operations at each point \(t\). The barycentric form computes the weights
\(w_i=1/\prod_{j\ne i}(x_i-x_j)\) once, and after that on the order of \(n\) operations suffice at
each point:
Moreover, it is numerically stable (J.-P. Berrut, L. N. Trefethen, Barycentric Lagrange Interpolation, SIAM Review 2004).
def runge(t):
return 1 / (1 + 25 * t**2)
def lagrange(X, Y, t):
s = 0.0
for i, (xi, yi) in enumerate(zip(X, Y)):
l = 1.0
for j, xj in enumerate(X):
if j != i:
l *= (t - xj) / (xi - xj)
s += yi * l
return s
n = 40
X = np.cos((2 * np.arange(n + 1) + 1) * np.pi / (2 * n + 2)) # Czebyszew
Y = runge(X)
siatka = np.linspace(-1, 1, 2001)
Xl, Yl, sl = X.tolist(), Y.tolist(), siatka.tolist()
czasy_interp = porownaj({
"wzór Lagrange'a": lambda: np.array([lagrange(Xl, Yl, t) for t in sl]),
"BarycentricInterpolator": lambda: BarycentricInterpolator(X, Y)(siatka)},
zgodne=lambda a, b: np.allclose(a, b, rtol=0, atol=1e-12))
blad = np.max(np.abs(BarycentricInterpolator(X, Y)(siatka) - runge(siatka)))
print(f"największy błąd interpolacji: {blad:.2e}")
wariant czas przyspieszenie
wzór Lagrange'a 94.7 ms 1.0×
BarycentricInterpolator 342 µs 277×
największy błąd interpolacji: 2.89e-04
The barycentric form is more than a hundred times faster. Both programs give the same values up to \(10^{-12}\).
Integration: the trapezoidal rule vs. quad#
The function scipy.integrate.quad uses the QUADPACK library. It applies a high-order
Gauss–Kronrod quadrature and subdivides the interval only where the error estimate is too large.
Let us count how many function values it needs for \(\int_0^1 e^{-x^2}dx\) and compare this with
the trapezoidal rule from Lecture 5.
wartosci = 0
def g(x):
global wartosci
wartosci += 1
return math.exp(-x * x)
def trapezy(f, a, b, n):
h = (b - a) / n
return h * (f(a) / 2 + sum(f(a + i * h) for i in range(1, n)) + f(b) / 2)
dokladnie = math.sqrt(math.pi) / 2 * math.erf(1)
print(f"{'metoda':18} {'wartości f':>10} {'błąd':>9}")
for n in (10, 100, 1000, 10000):
wartosci = 0
blad = abs(trapezy(g, 0, 1, n) - dokladnie)
print(f"{'trapezy, n = ' + str(n):18} {wartosci:10} {blad:9.1e}")
wartosci = 0
wynik, oszacowanie = scipy.integrate.quad(g, 0, 1)
wartosci_quad = wartosci
print(f"{'quad':18} {wartosci:10} {abs(wynik - dokladnie):9.1e}",
f" (oszacowanie błędu: {oszacowanie:.1e})")
czasy_calka = porownaj({"trapezy, n = 10000": lambda: trapezy(g, 0, 1, 10000),
"quad": lambda: scipy.integrate.quad(g, 0, 1)[0]},
zgodne=lambda a, b: abs(a - b) < 1e-8)
metoda wartości f błąd
trapezy, n = 10 11 6.1e-04
trapezy, n = 100 101 6.1e-06
trapezy, n = 1000 1001 6.1e-08
trapezy, n = 10000 10001 6.1e-10
quad 21 2.2e-16 (oszacowanie błędu: 8.3e-15)
wariant czas przyspieszenie
trapezy, n = 10000 795 µs 1.0×
quad 2.39 µs 333×
The trapezoidal rule needs ten thousand function values to reach an error on the order of
\(10^{-10}\). The function quad reaches machine precision after a few dozen values (the exact
number is in the table) and reports an error estimate. The trapezoidal rule does have its
advantages, though. It works on measured data, when the function values are known only at fixed
points. For periodic functions integrated over a full period, it is surprisingly accurate, as the
Euler–Maclaurin formula from Lab 7 shows.
Summary#
The LAPACK and BLAS libraries (through
np.linalgand the@operator) solve systems and multiply matrices hundreds and thousands of times faster than loops in Python. The advantage grows with the size.SciPy’s ready-made methods (
brentq,BarycentricInterpolator,quad) are not only faster: they compute fewer function values, they are stable, and they estimate the error.When we need an exact result, we compute with rational numbers. A general-purpose symbolic library can then be slower than simple code on
Fraction.Checking is cheaper than computing: we verify the result of a fast, complicated program with a simple checker.
Exercises#
★ Measure
np.linalg.inv(A) @ bandnp.linalg.solve(A, b)for \(n=500\). Which version is faster? Also compare the norms of the residuals \(\|Ax-b\|\).★ Compute the number of function values in bisection from the formula \(\lceil\log_2((b-a)/\varepsilon)\rceil+1\) and compare it with the counter
wywolania.★★ Write your own barycentric interpolation function (the weights and the formula from the text) and compare it with
BarycentricInterpolator. What happens when \(t\) is equal to one of the nodes?★★ Solve the system with the Hilbert matrix \(H_{12}\) exactly, and then check the solution with the checker
sprawdz. Measure both times.