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

An expression is a tree

Mul Pow sin Add Integer(2) Symbol('x') Symbol('x') Integer(1)
  • internal nodes: operations (Add, Mul, Pow, functions)
  • leaves: symbols and numbers
  • there is no subtraction or division:
    x - y = Add(x, Mul(-1, y))
    x/y = Mul(x, Pow(y, -1))

>>> e = (x + 1)**2 * sp.sin(x)
>>> sp.srepr(e)
"Mul(Pow(Add(Symbol('x'), Integer(1)), Integer(2)), sin(Symbol('x')))"
>>> type(e).__name__, e.args
('Mul', ((x + 1)**2, sin(x)))
  
Lecture 2 · Part I — How a CAS works Applet: expression tree → Open in the book →

Simplification: automatic versus on demand

Automatic — when the object is created


>>> x + x, x*x, 2*x*3
(2*x, x**2, 6*x)
>>> y + x + x      # spłaszczanie, porządek
2*x + y
>>> (x + 1)**2     # NIE rozwija sam!
(x + 1)**2
      

Automatic rules must be cheap and always correct.

On demand — explicit functions


>>> sp.expand((x + 1)**2)
x**2 + 2*x + 1
>>> sp.factor(x**3 - x)
x*(x - 1)*(x + 1)
>>> sp.cancel((x**2 - 1)/(x - 1))
x + 1
>>> sp.trigsimp(2*sp.sin(x)*sp.cos(x))
sin(2*x)
>>> sp.simplify(sp.sin(x)**2 + sp.cos(x)**2)
1
      
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).
Lecture 2 · Part I — How a CAS works Open in the book →

Exact and approximate arithmetic in a CAS

Exact


>>> sp.factorial(30)
265252859812191058636308480000000
>>> sp.Rational(1, 3) + sp.Rational(1, 6)
1/2
>>> sp.sqrt(8)              # liczba algebraiczna
2*sqrt(2)
>>> sp.sqrt(2).evalf(30)    # precyzja na żądanie
1.41421356237309504880168872421
      

Approximation: Float with a given precision


>>> sp.Float(0.1, 30)     # binarne 0.1
0.100000000000000005551115123126
>>> sp.Float('0.1', 30)   # dziesiętne 0.1
0.100000000000000000000000000000
      
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).
Lecture 2 · Part I — How a CAS works Open in the book →

Canonical form and normal form

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

>>> f = (x**2 - 1)*(x + 2)/(x**2 + 3*x + 2)
>>> sp.cancel(f)            # p/q, NWD(p, q) = 1
x - 1
>>> sp.gcd(x**3 - 1, x**2 - 1)
x - 1
    
For polynomials and rational functions the problem “is $f = g$?” is solved: reduce to canonical form and compare.
Lecture 2 · Part I — How a CAS works Applet: canonical form → Open in the book →
🤿deep dive

When a CAS proves: the circle group

The circle $a^2+b^2=1$ with the operation $(a,b)\cdot(c,d)=(ac-bd,\ ad+bc)$ is a group. Closure is a polynomial identity

$(ac-bd)^2+(ad+bc)^2=(a^2+b^2)(c^2+d^2)$,

and the canonical form decides it — just by expanding the brackets:


>>> a, b, c, d = sp.symbols('a b c d')
>>> sp.expand((a*c - b*d)**2 + (a*d + b*c)**2
...           - (a**2 + b**2)*(c**2 + d**2))
0
      

in the deep dive

  • powers of a point give the Chebyshev polynomials: $P^n = (T_n(a),\ b\,U_{n-1}(a))$, and $(P^n)^m = P^{mn}$ is the composition $T_m\circ T_n = T_{mn}$
  • $\cos\frac{2\pi}{17}$ from three quadratic equations (Gauss), the 15-gon by multiplying points
  • the circle over $\F_p$, Pell’s equation, the Lucas–⁠Lehmer test
  • part 5, very advanced: the Lie group, dual numbers $\varepsilon^2 = 0$, Machin’s formula for $\pi$
Every step ends with a check that the CAS performs exactly — the canonical form turns a computation into a proof.
Lecture 2 · Part I — How a CAS works Applet: the circle group → 🤿 Deep dive: the circle group →
Limits of the possible

The zero problem is undecidable

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

>>> (x + 1)**2 == x**2 + 2*x + 1   # te same drzewa?
False
>>> ((x + 1)**2).equals(x**2 + 2*x + 1)
True
>>> (sp.sin(x)**2 + sp.cos(x)**2).equals(1)
True
    
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.
Lecture 2 · Part I — How a CAS works Applet: checking identities → 🤿 Deep dive: full proof →

Branches of functions and assumptions


>>> 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.
Lecture 2 · Part I — How a CAS works Open in the book →
Part II

Representing numbers

integers · fixed point · floating point · binary64

Numerics lies

Rump’s example: exact data, an absurd result

$f(a,b) = 333.75\,b^6 + a^2\,(11a^2b^2 - b^6 - 121b^4 - 2) + 5.5\,b^8 + \dfrac{a}{2b}$,   $a = 77617,\ b = 33096$

float64


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.
Lecture 2 · Part II — Representing numbers Applet: float vs exact → Open in the book →

Integers: arbitrary length and fixed width

Python int versus NumPy int64


>>> math.factorial(21)
51090942171709440000
>>> s = np.cumprod(np.arange(1, 22, dtype=np.int64))
>>> print(s[-1])                    # 21! w int64
-4249290049419214848
>>> math.factorial(21) % 2**64 - 2**64
-4249290049419214848
      
  • 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.
Lecture 2 · Part II — Representing numbers Open in the book →

Fixed-point representation: constant absolute error

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.8relative errorbinary16relative error
0.0010100%0.0010004$4.0\cdot10^{-4}$
0.010.011718817%0.0100021$2.1\cdot10^{-4}$
0.10.1015621.6%0.0999756$2.4\cdot10^{-4}$
100.3100.301$7.8\cdot10^{-6}$100.312$1.2\cdot10^{-4}$
1000.7overflow—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.
Lecture 2 · Part II — Representing numbers Open in the book →

A float from the inside (IEEE 754, binary64)

0 01111111011 1001100110011001100110011001100110011001100110011010 0.1 in the computer’s memory: s exponent e = 1019 significand f (52 bits) x = (−1)s · (1.f)2 · 2e − 1023    ⇒    0.1 ≈ (1.1001 1001 …)2 · 2−4

>>> 0.1 + 0.2
0.30000000000000004
>>> (1e16 + 1) - 1e16
0.0
>>> from decimal import Decimal
>>> print(Decimal(0.1))
0.1000000000000000055511151231257827021181583404541015625
    

Python float = C double; NumPy = C loops over whole arrays — billions of operations per second.

  • about 15–17 significant digits; $\varepsilon = 2^{-52} \approx 2.22\cdot 10^{-16}$; range up to about $10^{\pm 308}$
  • every operation: the exact result rounded to the nearest machine number
  • $0.1$ has no finite binary expansion (just as $\tfrac13$ has no finite decimal one)
Lecture 2 · Part II — Representing numbers Applet: anatomy of a float → Open in the book →

Floating-point representation and binary64

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
binary64531023Python float, C double
binary3224127C float, graphics cards
binary161115machine 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.17,205,759,403,792,794−5653
2.0**-10224,503,599,627,370,496−107453
1e-3202024−107411
5e-3241−10741

Normal numbers have 53-bit significands; below $2^{-1022}$ the exponent stays at $-1074$ and bits are lost.

Lecture 2 · Part II — Representing numbers Open in the book →

Machine numbers on the number line

0 1 2 3 4 5 6 7 8 fixed point, step 1/4 𝔽(2, 3, −1, 2) [2⁻¹, 2⁰) [2⁰, 2¹) [2¹, 2²) [2², 2³) subnormal
  • the toy system $\F(2, 3, -1, 2)$: 16 normal numbers, 4 in each interval $[2^{e}, 2^{e+1})$ — the spacing doubles at every power of two
  • 3 subnormal numbers $\tfrac18, \tfrac14, \tfrac38$ fill the gap between $0$ and $\tfrac12$ with the same spacing $\tfrac18$
  • fixed point: constant spacing; floating point: dense near zero, sparse far from it
Lecture 2 · Part II — Representing numbers Applet: density of numbers, a toy system → Open in the book →

Spacing: ulp, ε and u

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$.
2 − 2 2 − 1 2 0 2 1 2 2 2 3 2 4 x 1.00 1.25 1.50 1.75 2.00 ulp(x) / (x·u) ε = 2u u

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$.

Lecture 2 · Part II — Representing numbers Open in the book →
🤿deep dive

Range and subnormal numbers

numbervalue
largest finite $(2-2^{-52})\cdot2^{1023}$$\approx 1.80\cdot10^{308}$
smallest positive normal $2^{-1022}$$\approx 2.23\cdot10^{-308}$
smallest positive subnormal $2^{-1074}$$\approx 4.94\cdot10^{-324}$

Overflow: sys.float_info.max * 2 gives inf.

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.

Lecture 2 · Part II — Representing numbers 🤿 Deep dive: gradual underflow → Open in the book →
Part III

Rounding and arithmetic

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
Lecture 2 · Part III — Rounding and arithmetic 🤿 Deep dive: rounding modes → Open in the book →

The error model — and checking it

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
−1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 δ / u (20,000 random products) 0 200 400 600 number of pairs

$\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})$.

Lecture 2 · Part III — Rounding and arithmetic Open in the book →
🤿deep dive

Why do we break ties to even?

drift in three-digit arithmetic

$u \leftarrow (u + v) - v$ for $u = 1.00$, $v = 0.555$, 3 decimal digits

tie rulesuccessive values of $u$
round half up1.00 → 1.01 → 1.02 → 1.03 → 1.04 → …
ties to even1.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.

Lecture 2 · Part III — Rounding and arithmetic 🤿 Deep dive: ties to even → Open in the book →

Which laws of arithmetic survived?

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)

lawfails in
(a+b)+c != a+(b+c)17.05%
(a*b)*c != a*(b*c)34.84%
a*(b+c) != a*b+a*c31.21%
a+b != b+a or a*b != b*a0.00%

A compiler that reorders operations for speed (-ffast-math) changes the result of the program.

Lecture 2 · Part III — Rounding and arithmetic Open in the book →
🤿deep dive

What does summation cost?

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

methoderrorin 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.

Lecture 2 · Part III — Rounding and arithmetic 🤿 Deep dive: Kahan, Neumaier, fsum → Open in the book →
🤿deep dive

Sterbenz’s lemma: exact subtraction

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.
Lecture 2 · Part III — Rounding and arithmetic 🤿 Deep dive: Sterbenz’s lemma → Open in the book →
Part IV

Errors and guarantees

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 error488
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.
Lecture 2 · Part IV — Errors and guarantees Open in the book →

Conditioning of a problem

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$.
Lecture 2 · Part IV — Errors and guarantees Open in the book →

Catastrophic cancellation: $(1 + 10^{-15}) - 1$


>>> 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.
Lecture 2 · Part IV — Errors and guarantees Open in the book →

Stability of an algorithm

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).
Lecture 2 · Part IV — Errors and guarantees Open in the book →

The smaller root of $x^2 - bx + 1 = 0$

A well-conditioned problem (SymPy, $b = 10^{8}$):
$\kappa$ with respect to $b$: $1.00000$, with respect to $c$: $1.00000$.

two algorithms

schoolbook: $x_2 = \bigl(b - \sqrt{b^2 - 4c}\bigr)/2$
Viète: $x_1 = \bigl(b + \sqrt{b^2 - 4c}\bigr)/2$, $\ x_2 = c/x_1$

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 errorViè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.

Lecture 2 · Part IV — Errors and guarantees Open in the book →
🤿deep dive

$(1 + 1/n)^n$: theory predicts the error

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$naivewith log1p
$10^{15}$3.0350352065492622.7182818284590438
$10^{16}$1.02.718281828459045

Reference value for $n = 10^{16}$: $2.7182818284590451$. A plot for $n$ up to $10^{17}$: deep dive, part 2, §7.

Lecture 2 · Part IV — Errors and guarantees 🤿 Deep dive: (1+1/n)ⁿ and log1p → Open in the book →
🤿deep dive

Muller’s sequence: ill-conditioned problem

5 10 15 20 25 30 n 0 20 40 60 80 100 uₙ float exact (Fraction)

$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.
Lecture 2 · Part IV — Errors and guarantees Lab 3: exercise D1 → 🤿 Deep dive: Muller → Open in the book →

An honest answer: interval arithmetic

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

digitsinterval containing $f(77617, 33096)$
15$[-5.9\cdot10^{21},\ 4.7\cdot10^{21}]$ — an honest “I don’t know”
30$[-1048574.83\ldots,\ 1048577.17\ldots]$
40$-0.827396059946821368141165095479816\ldots$  (interval width $\approx 2.3\cdot10^{-41}$)

Intervals do not lie — at worst they say “not enough precision”.

  • W. Tucker (2002): existence of the Lorenz attractor (Smale’s 14th problem) — interval computations
  • T. Hales (1998): the Kepler conjecture — massive computations; the formal proof Flyspeck (2014, publ. 2017)
  • tools: mpmath.iv, Arb (now part of FLINT)
Lecture 2 · Part IV — Errors and guarantees Open in the book →

The pyramid of trust

formal proof symbolic computation (CAS — exact, no certificate) numerical experiment (fast and broad, no guarantee) certainty ↑ cost ↑ reach ↓
QuestionTool
What is it approximately? What does the graph look like?numerics
Is the conjecture plausible? Is there a formula?numerics + CAS
What is the exact result, factorization, formula?CAS
Is the numerical result rigorous?interval arithmetic
Is it true for all $n$?proof (paper, Peano Lab, Lean)
Lecture 2 · Part IV — The pyramid of trust Open in the book →

Summary

✓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).
●Representation: int64 = $\Z/2^{64}\Z$; fixed point — constant absolute error, floating point — constant relative error. Binary64: $p = 53$, $\varepsilon = 2^{-52}$, $u = 2^{-53}$.
●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.
Lecture 2 · summary Chapter in the book →

Thank you!

Date and topic of the next lecture: Harmonogram (in Polish) on the course website.

🤿 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

ESC slide overview · S speaker notes · ? keyboard shortcuts