Komputerowe rozwiązywanie problemów matematycznych · lecture
Lecture 2: Computer algebra and floating-point numbers
how a CAS works · representing numbers · one rounding rule · conditioning and stability · interval arithmetic
symbolic computation (CAS)numericsguarantee
Dr. Bartosz Naskręcki · Wydział Matematyki i Informatyki UAM · 06-S1MA03-P16780 winter semester 2026/27 · course taught in Polish — dates and rooms: Harmonogram (in Polish)
Lecture outline
I
How a CAS works
expression = tree · simplification · canonical form · the zero problem · branches and assumptions
18 min
II
Representing numbers
Rump’s example · int64 · fixed- and floating-point representation · binary64 · ulp, ε, u
20 min
III
Rounding and arithmetic
one rule · the error model · which laws of arithmetic survived
11 min
IV
Errors and guarantees
conditioning · cancellation · stability · interval arithmetic · the pyramid of trust
19 min
✓
Summary
what to remember, where to read more
3 min
symbolic computation and exact verification (SymPy, Fraction)
numerical computation (float)
guarantee: theorem, interval arithmetic
🤿 deep dive only announced in the lecture — details in the book’s deep dives
Lecture 2 · outline
Part I
How does a computer algebra system work?
representation · simplification · canonical form · limits
Which is “simpler”: $(x+1)^2$ or $x^2+2x+1$? It depends on the goal — that is why a CAS has many simplification functions, and simplify tries several strategies and picks the result with the fewest operations (count_ops).
The number 0.1 typed in Python is already an approximation — increasing the precision afterwards will not restore the lost information.
A CAS computes exactly for as long as it can (big integers, fractions, algebraic numbers). Approximation (evalf, N) is a deliberate decision by the user, with controlled precision (the mpmath library).
Canonical form: every expression in a given class has exactly one representation ⇒ equality = comparison of trees. Normal form: zero has a single representation ⇒ $f = g \iff \mathrm{normal}(f-g) = 0$.
polynomials: expanded, with ordered monomials — a canonical form
rational functions: $p/q$ with $\gcd(p,q)=1$ and monic $q$ — a canonical form
this requires the polynomial GCD — the Euclidean algorithm for polynomials
Theorem (D. Richardson, 1968). For expressions built from $x$, rational numbers, $\pi$, $\ln 2$ and the functions $\sin$, $\exp$, $|\cdot|$ by means of addition, multiplication and composition, there is no algorithm that decides whether a given expression is identically equal to $0$. D. Richardson, Some undecidable problems involving elementary functions of a real variable, J. Symbolic Logic 33 (1968).
⇒ there is no canonical form for such expressions
⇒ simplify is a heuristic: it may fail to find a zero
⇒ a CAS combines rules, numerical tests and assumptions
In SymPy, == asks “is this the same tree?”, not “is this the same function?”. The method .equals() simplifies the difference and, if necessary, checks it numerically — this is a verification, not a proof.
>>> sp.sqrt(x**2)
sqrt(x**2)
>>> r = sp.symbols('r', real=True); sp.sqrt(r**2)
Abs(r)
>>> p = sp.symbols('p', positive=True); sp.sqrt(p**2)
p
>>> a, b = sp.symbols('a b'); sp.expand_log(sp.log(a*b))
log(a*b)
>>> sp.log(-1) + sp.log(-1), sp.log((-1)*(-1))
(2*I*pi, 0)
>>> f = (x**2 - 1)/(x - 1)
>>> f.subs(x, 1), sp.cancel(f).subs(x, 1)
(nan, 2)
$\sqrt{x^2} = |x|$, not $x$ — unless $x \ge 0$
the complex logarithm has branches: $\log((-1)(-1)) = 0$, but $\log(-1) + \log(-1) = 2\pi i$
the cancellation $\frac{x^2-1}{x-1} = x+1$ has “lost” the point $x = 1$
Every simplification rule has conditions of applicability. A CAS must know the assumptions — otherwise it either does not simplify or simplifies incorrectly.
a, b = 77617.0, 33096.0
f = 333.75*b**6 + a**2*(11*a**2*b**2 - b**6 - 121*b**4 - 2) + 5.5*b**8 + a/(2*b)
print(f) # -1.1805916207174113e+21
exact: fractions.Fraction
from fractions import Fraction as Fr
a, b = Fr(77617), Fr(33096)
f = Fr(33375, 100)*b**6 + a**2*(11*a**2*b**2 - b**6 - 121*b**4 - 2) + Fr(11, 2)*b**8 + a/(2*b)
print(f, float(f)) # -54767/66192 -0.8273960599468214
The float result has the wrong sign and is off by 21 orders of magnitude — although all the data are exactly representable. The cause: catastrophic cancellation — two terms of order $\pm 7.9\cdot10^{36}$ almost cancel and wipe out all significant digits.
the first wrong factorial in int64: $21!$; the largest int64 is $2^{63}-1 = 9\,223\,372\,036\,854\,775\,807$
NumPy arrays raise neither an error nor a warning
A fixed width of $n$ bits = the ring $\Z/2^{n}\Z$: addition and multiplication modulo $2^{n}$, with the result stored as a representative from $[-2^{n-1}, 2^{n-1})$ (two’s complement).
The computation in int64 is correct in $\Z/2^{64}\Z$, but not in $\Z$: $21! \bmod 2^{64} = 14\,197\,454\,024\,290\,336\,768$, and this is exactly the int64 result plus $2^{64}$.
Python int: always exact, but the cost of an operation grows with the length of the numbers.
Definition.Fixed-point representation: $x = m\cdot\beta^{-k}$, $m \in \Z$, $|m| < \beta^{n}$. The spacing is $\beta^{-k}$ everywhere, so the rounding error is $\le \tfrac12\beta^{-k}$ regardless of the size of $x$. Amounts in cents ($\beta = 10$, $k = 2$): sums are exact.
Two 16-bit representations: Q8.8 ($m/2^{8}$, $|m| < 2^{15}$) and binary16 (np.float16); errors computed with fractions:
$x$
Q8.8
relative error
binary16
relative error
0.001
0
100%
0.0010004
$4.0\cdot10^{-4}$
0.01
0.0117188
17%
0.0100021
$2.1\cdot10^{-4}$
0.1
0.101562
1.6%
0.0999756
$2.4\cdot10^{-4}$
100.3
100.301
$7.8\cdot10^{-6}$
100.312
$1.2\cdot10^{-4}$
1000.7
overflow
—
1000.5
$2.0\cdot10^{-4}$
Q8.8: good for $100$, useless for $0.001$, ends at $128$. Binary16: relative error $\le 2^{-11} \approx 4.9\cdot10^{-4}$ from about $6\cdot10^{-5}$ to $65\,504$. Constant relative error over a huge range.
Definition. The system $\F(\beta, p, e_{\min}, e_{\max})$: zero and the numbers
$x = \pm(d_0.d_1\ldots d_{p-1})_\beta\cdot\beta^{e}$ with exponent $e_{\min} \le e \le e_{\max}$. Normal numbers have $d_0 \ne 0$, and subnormal ones have $e = e_{\min}$ and $d_0 = 0$. Equivalently, $x = \pm M\cdot\beta^{e-p+1}$ with an integer significand $0 < M < \beta^{p}$.
format
$p$
$e_{\max}$
where
binary64
53
1023
Python float, C double
binary32
24
127
C float, graphics cards
binary16
11
15
machine learning
$e_{\min} = 1 - e_{\max}$. Binary64: 1 sign bit, 11 exponent bits, 52 significand bits (the leading digit, always 1, is not stored) — previous slide.
significand M and exponent E
$|x| = M\cdot2^{E}$, computed with math.frexp and checked with fractions
$x$
$M$
$E$
bits of $M$
0.1
7,205,759,403,792,794
−56
53
2.0**-1022
4,503,599,627,370,496
−1074
53
1e-320
2024
−1074
11
5e-324
1
−1074
1
Normal numbers have 53-bit significands; below $2^{-1022}$ the exponent stays at $-1074$ and bits are lost.
Definition. For $2^{e} \le |x| < 2^{e+1}$, $-1022 \le e \le 1023$: $\ulp(x) = 2^{e-52}$ (unit in the last place); for $|x| < 2^{-1022}$: $\ulp(x) = 2^{-1074}$. Machine epsilon: $\varepsilon = \ulp(1) = 2^{-52} \approx 2.22\cdot10^{-16}$. Unit roundoff: $u = \varepsilon/2 = 2^{-53} \approx 1.11\cdot10^{-16}$.
For $x$ in the range of normal numbers
$$|\fl(x) - x| \le \tfrac12\ulp(x) \le u\,|x| :$$
the relative representation error is $\le u$, about 16 digits, regardless of the order of magnitude of $x$.
Relative spacing $\ulp(x)/x$ for binary64 (computed with math.ulp): in each $[2^{e}, 2^{e+1})$ it decreases from $2u$ to just above $u$.
Puzzle: how many times can you divide 1.0 by 2 before you get zero? 1075
1022 divisions down to $2^{-1022}$, then 52 exact divisions in the subnormal range down to $2^{-1074}$; $2^{-1075}$ is a tie between $0$ and $2^{-1074}$ — zero wins (even significand).
Subnormal numbers = fixed point near zero: $2^{52} - 1$ positive numbers, multiples of $2^{-1074}$, equally spaced. They lose relative precision, but they fill the gap: gradual underflow.
Thanks to them, for finite $x, y$: $\quad x \ne y \iff x - y \ne 0$, so the test if x != y: protects a division by $x - y$.
Kahan’s argument and a simulation of a processor without subnormal numbers (flush to zero): IEEE 754 deep dive, §4; exercise B1 in Lab 3.
one rule · the error model · the laws that survived
One rule: correct rounding
Definition. $\fl(x)$ — the machine number nearest to $x$; in a tie, the one with even significand $M$ (round to nearest, ties to even); for $|x| \ge (2-2^{-53})\cdot2^{1023}$ the result is $\pm\infty$.
The rule of correct rounding (IEEE 754). For machine numbers $x, y$ and $\circ \in \{+, -, \cdot, /\}$, the result of the operation is
$$x \circledcirc y = \fl(x \circ y),$$
i.e., the exact result, rounded. The same holds for $\sqrt{x}$ and for conversions (e.g., from decimal notation).
directed modes: toward $0$, $+\infty$, $-\infty$ — interval arithmetic rests on them (Part IV)
the functions sin, exp, log: the standard only recommends correct rounding; libraries are usually off by less than 1 ulp or by a few ulp
a reference for checking: Fraction computes exactly, and float(q) rounds correctly
Corollary. If the exact result lies in the range of normal numbers, then
$$\fl(x \circ y) = (x \circ y)(1 + \delta),$$
where $|\delta| \le u = 2^{-53}$. Proof: $\delta = (\fl(z) - z)/z$, $|\fl(z) - z| \le u|z|$.
experiment: Fraction as the reference
20,000 random pairs (exponents $-60$ to $60$), 4 operations: 80,000 results, 0 mismatches
the largest $|\delta|/u$ for multiplication: $0.995844$ — close to $1$, but never above
$72\%$ of the products have $|\delta| \le u/2$: the model is the worst case
$\delta/u$ computed exactly (Fraction) for 20,000 products. Values close to $\pm u$ occur only when the result lies near the lower end of its $[2^{e}, 2^{e+1})$.
$u \leftarrow (u + v) - v$ for $u = 1.00$, $v = 0.555$, 3 decimal digits
tie rule
successive values of $u$
round half up
1.00 → 1.01 → 1.02 → 1.03 → 1.04 → …
ties to even
1.00 → 1.00 → 1.00 → 1.00 → 1.00 → …
Computed with the decimal module (precision 3). Mathematically, $(u+v)-v = u$.
rounding halves up is biased: the errors accumulate
with ties to even such a sequence does not drift for any $u, v$ (Reiser, Knuth 1975)
We have already seen ties:
• round(2.5) == 2 (Lecture 1, §1.2)
• $2^{-1075} \to 0$ in the halving puzzle
• $10^{16} + 1 \to 10^{16}$ (Part II)
The proof that there is no drift, and a measurement of the bias — IEEE 754 deep dive, §3. In exercise A1 of Lab 3 you will find drifting sequences of your own.
They hold (for finite numbers), because they follow directly from the rule:
• commutativity: $x \oplus y = y \oplus x$, $x \otimes y = y \otimes x$
• identity elements: $x \oplus 0 = x$, $x \otimes 1 = x$
• monotonicity ($\fl$ is nondecreasing): $a \le b \Rightarrow a \oplus c \le b \oplus c$
They fail: associativity and distributivity — two operations mean two roundings, and their effect depends on the order.
100,000 random triples from [0, 1)
law
fails in
(a+b)+c != a+(b+c)
17.05%
(a*b)*c != a*(b*c)
34.84%
a*(b+c) != a*b+a*c
31.21%
a+b != b+a or a*b != b*a
0.00%
A compiler that reorders operations for speed (-ffast-math) changes the result of the program.
Lemma. $|\delta_i| \le u$, $ku < 1$ $\Rightarrow$ $\prod_{i=1}^{k}(1+\delta_i) = 1 + \theta_k$, $|\theta_k| \le \gamma_k := \frac{ku}{1-ku}$. Theorem. The sum computed in a loop satisfies
$$\Bigl|\hat s - \sum x_i\Bigr| \le \gamma_{n-1}\sum|x_i|$$
i.e., approximately $(n-1)\,u\sum|x_i|$ (N. J. Higham 2002, ch. 4).
Pitfall:sum([0.1]*10) == 1.0 is true: since Python 3.12, sum() of floats uses compensation (Neumaier). A loop gives 0.9999999999999999.
harmonic sum, a million terms, binary64
method
error
in ulp
forward loop
$-7.35\cdot10^{-13}$
−413.62
backward loop
$4.86\cdot10^{-14}$
27.38
np.sum (pairwise)
$2.44\cdot10^{-15}$
1.38
sum(), math.fsum
$6.67\cdot10^{-16}$
0.38
The bound from the theorem: $1.6\cdot10^{-9}$ — true, but more than a thousand times too pessimistic. The error of math.fsum comes from representing the terms $1/k$, not from the summation.
Sterbenz’s lemma (1974). If $x, y$ are binary64 machine numbers and $\tfrac{y}{2} \le x \le 2y$, then $x - y \in \F$, so $x \ominus y = x - y$ exactly.
proof sketch
Let $y \le x \le 2y$, $2^{e} \le y < 2^{e+1}$, $q = 2^{\max(e, -1022) - 52}$. Machine numbers $\ge y$ are multiples of $q$, so $x - y = Mq$, and from $x - y \le y < 2^{e+1}$ we get $M < 2^{53}$. Such a number belongs to $\F$, so rounding does not change it. $\blacksquare$
verification: 20,000 random pairs
$x$
inexact $x - y$
$\tfrac{y}{2} \le x \le 2y$
0 / 20,000
$\tfrac{y}{8} \le x < \tfrac{y}{2}$
7728 / 20,000
Conclusion: subtracting nearby numbers introduces no error. So where does “catastrophic cancellation” come from? — Part IV.
problem conditioning · cancellation · algorithm stability · interval arithmetic
Absolute and relative error
Definition. For an approximation $\hat x$ of a number $x$: the absolute error is $|\hat x - x|$, the relative error is $|\hat x - x|/|x|$ ($x \ne 0$). A relative error $\approx 10^{-d}$ means about $d$ correct significant digits.
example: Ramanujan’s constant — is it an integer?
value
math.exp(math.pi * math.sqrt(163))
262,537,412,640,768,256
exact (mpmath, 50 digits)
262,537,412,640,768,743.999 999 999 999 25…
absolute error
488
relative error
$1.86\cdot10^{-15}$ — almost 15 correct digits
Which error matters depends on the question: for the question “is it an integer?” a result with 15 good digits is useless.
Definition. For a differentiable $f$ and $f(x) \ne 0$, the condition number is
$$\kappa_f(x) = \left|\frac{x\,f'(x)}{f(x)}\right| .$$
By Taylor’s formula: $f\bigl(x(1+\delta)\bigr) \approx f(x)\bigl(1 + \kappa_f(x)\,\delta\bigr)$.
x = sp.symbols("x", positive=True)
sp.simplify(x * sp.diff(f, x) / f)
condition numbers computed in SymPy
$f(x)$
$\kappa_f(x)$
ill-conditioned
$x - 1$
$\left|\frac{x}{x-1}\right|$
near $x = 1$
$\sqrt{x}$
$\frac12$
never
$e^{x}$
$|x|$
for large $|x|$
$x^{n}$
$n$
for large $n$
$\log x$
$\frac{1}{|\log x|}$
near $x = 1$
$\sin x$
$\left|\frac{x}{\tan x}\right|$
near $k\pi$, $k \ne 0$
$e^{\pi\sqrt{163}}$: the argument $\approx 40.1$ is rounded with a relative error of order $u$, and $\exp$ multiplies it by $\kappa \approx 40$.
>>> a = 1 + 1e-15 # jedno zaokrąglenie
>>> a - 1
1.1102230246251565e-15
>>> Fraction(a) - 1 == Fraction(a - 1)
True # odejmowanie dokładne!
relative representation error of $a$
$1.10\cdot10^{-16}$
$\kappa(x - 1)$ at the point $1 + 10^{-15}$
$\approx 10^{15}$
relative error of the result
$0.110$, i.e., 11%
Prediction: $\kappa \cdot u \approx 10^{15}\cdot1.11\cdot10^{-16} \approx 0.11$. It agrees.
Catastrophic cancellation is the ill-conditioning of subtracting nearby numbers. The subtraction is exact — it only brings to the surface an error stored earlier in the data.
Definition. An algorithm $\hat f$ for computing $f$ is backward stable if for all data $x$
$$\hat f(x) = f(\hat x) \quad\text{for some } \hat x,\ |\hat x - x| \le C u|x| ,$$
i.e., it gives the exact answer to a slightly perturbed question. Then the relative error of the result is $\lesssim \kappa_f(x)\cdot Cu$.
A single IEEE 754 operation is backward stable: $\fl(x + y) = x(1+\delta) + y(1+\delta)$.
An unstable algorithm usually solves an ill-conditioned subproblem along the way, even though the problem as a whole is well conditioned.
Rule of thumb: error of the result $\approx$ conditioning of the problem $\times$ (data error $+$ error introduced by the algorithm).
The schoolbook formula subtracts numbers that agree in almost all digits: an error of order $u\,b$ in $\sqrt{\cdot}$, against a result of order $c/b$, gives a relative error $\approx u\,b^2/c$.
$b$
schoolbook formula error
Viète’s formula error
$10^{4}$
$1.1\cdot10^{-9}$
$5.7\cdot10^{-17}$
$10^{6}$
$7.6\cdot10^{-6}$
$8.9\cdot10^{-17}$
$10^{8}$
$2.5\cdot10^{-1}$
$7.9\cdot10^{-17}$
$10^{10}$
$1.0$ (result $0$)
$3.6\cdot10^{-17}$
Relative errors against mpmath values (50 digits). For $b = 10^{8}$: schoolbook 7.450580596923828e-09 (exactly $2^{-27}$), Viète 1e-08.
Algorithm: y = 1 + 1/n in float, then $y^{n}$. The power has $\kappa = n$, so a relative error $\delta$ in $y$ gives an error in the result $\approx n\delta$. We compute $\delta$ exactly (Fraction):
$n$
$\delta$ for $y$
prediction $n\delta$
error of the result
$10^{8}$
$-6.08\cdot10^{-17}$
$-6.08\cdot10^{-9}$
$-6.08\cdot10^{-9}$
$10^{12}$
$8.89\cdot10^{-17}$
$8.89\cdot10^{-5}$
$8.89\cdot10^{-5}$
$10^{14}$
$-7.99\cdot10^{-18}$
$-7.99\cdot10^{-4}$
$-7.99\cdot10^{-4}$
$10^{15}$
$1.10\cdot10^{-16}$
$0.110$
$0.117$
The error of the result is measured against the exact $(1 + 1/n)^n$ (mpmath), not against $e$. For $n = 10^{15}$ the more precise prediction $e^{n\delta} - 1 = 0.117$ also agrees.
Stably: $(1+1/n)^n = \exp\bigl(n\log(1 + 1/n)\bigr)$, and math.log1p(t) computes $\log(1+t)$ without forming $1 + t$.
$n$
naive
with log1p
$10^{15}$
3.035035206549262
2.7182818284590438
$10^{16}$
1.0
2.718281828459045
Reference value for $n = 10^{16}$: $2.7182818284590451$. A plot for $n$ up to $10^{17}$: deep dive, part 2, §7.
$u_0 = 2$, $u_1 = -4$, $u_{n+1} = 111 - \frac{1130}{u_n} + \frac{3000}{u_n u_{n-1}}$. The exact terms (Fraction) tend to $6$; float jumps to $100$ after a dozen or so steps: $u_{30} = 99.99999999999993$ instead of $6.00564868877142$.
condition number measured with fractions
the problem $u_1 \mapsto u_n$; $u_1$ perturbed by $10^{-40}$
$n$
$\kappa_n$
5
$1.07\cdot10^{4}$
10
$9.40\cdot10^{9}$
15
$1.07\cdot10^{16}$
20
$1.32\cdot10^{22}$
30
$2.13\cdot10^{34}$
$\kappa_n$ grows about $100/6 \approx 16.7$ times per step; at $n \approx 15$ we have $\kappa_n u \approx 1$. More digits only postpone the disaster — how many steps 50 digits gain: Lab 3, exercise D1.
Interval arithmetic: instead of a number $x$ we keep an interval $[a,b] \ni x$; every operation rounds the endpoints outward ⇒ the result is guaranteed to contain the true value.
Rump’s example in mpmath.iv
digits
interval containing $f(77617, 33096)$
15
$[-5.9\cdot10^{21},\ 4.7\cdot10^{21}]$ — an honest “I don’t know”
✓CAS: expression = tree; simplification is automatic (cheap, always correct) or on demand. Polynomials and rational functions have a canonical form, so equality is decidable.
✗The zero problem is undecidable (Richardson) ⇒ simplify is a heuristic; every simplification rule has assumptions (branches, domains).
●One rule: result of an operation = the exact result, rounded; hence $\fl(x\circ y) = (x\circ y)(1+\delta)$, $|\delta| \le u$. Associativity and distributivity fail.
●Error of the result ≈ conditioning × (data error + algorithm error). Cancellation = ill-conditioned subtraction; the schoolbook formula for the root — an unstable algorithm.
✓Guarantee: interval arithmetic does not lie — for Rump’s example it says “I don’t know” at 15 digits and gives the result at 40.
🤿 Deep dives IEEE 754 from the inside subnormal numbers · ties to even · Sterbenz’s lemma · Kahan, Neumaier, fsum · $(1+1/n)^n$ and log1p · Muller’s sequence · from the Pentium bug to formal proofs Richardson’s theorem— the zero problem The circle group— purely symbolic proofs ·
applet