{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cc187805",
   "metadata": {},
   "source": [
    "# Errors: problem conditioning and algorithm stability\n",
    "\n",
    "The model from the previous section says that each operation introduces a relative error of at\n",
    "most $u \\approx 1.1\\cdot10^{-16}$. A program, however, performs thousands or billions of\n",
    "operations, and in Lecture 1 we saw that Rump’s example loses all its digits in a dozen or so\n",
    "operations. To predict when a computation is reliable, we need two notions. **Conditioning** is\n",
    "a property of the problem: it tells us how strongly the result depends on perturbations of the\n",
    "data. **Stability** is a property of the algorithm: it tells us whether the algorithm refrains from\n",
    "adding errors larger than the problem itself requires. Together they give a rule that we will test\n",
    "on several examples: the relative error of the result is approximately the conditioning of the\n",
    "problem times the sum of the relative error of the data and the error introduced by the algorithm.\n",
    "\n",
    "We need the standard library, NumPy, SymPy (for symbolic condition numbers), and mpmath, in which\n",
    "we compute reference values to 50 digits:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b49af10a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "from fractions import Fraction\n",
    "import numpy as np\n",
    "import sympy as sp\n",
    "import mpmath\n",
    "\n",
    "mpmath.mp.dps = 50                 # wartości wzorcowe liczymy z 50 cyframi"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e93cbd5",
   "metadata": {},
   "source": [
    "## Absolute and relative error\n",
    "\n",
    "```{admonition} Definition (absolute and relative error)\n",
    ":class: note\n",
    "Let $\\hat x$ be an approximation of a number $x$. The **absolute error** is $|\\hat x - x|$, and for\n",
    "$x \\neq 0$ the **relative error** is $|\\hat x - x| / |x|$. If the relative error is about $10^{-d}$,\n",
    "we say that $\\hat x$ has about $d$ correct significant digits.\n",
    "```\n",
    "\n",
    "The error model of an operation from the previous section concerns the relative error, and it is\n",
    "the relative error that is the natural measure in floating-point arithmetic. Ramanujan’s constant\n",
    "from Lecture 1 illustrates this well: let us compute $e^{\\pi\\sqrt{163}}$ in `float` and to\n",
    "50 digits."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5b1a0cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "v = math.exp(math.pi * math.sqrt(163))\n",
    "V = mpmath.exp(mpmath.pi * mpmath.sqrt(163))\n",
    "print(\"float:\", v, \"  dokładnie:\", mpmath.nstr(V, 33))\n",
    "print(\"błąd bezwzględny:\", mpmath.nstr(abs(v - V), 5),\n",
    "      \"  błąd względny:\", mpmath.nstr(abs(v - V) / V, 5))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2229b5c7",
   "metadata": {},
   "source": [
    "The absolute error is several hundred, and the relative error is $1.9\\cdot10^{-15}$: the result has\n",
    "almost 15 correct significant digits, and yet it is completely useless for deciding whether\n",
    "$e^{\\pi\\sqrt{163}}$ is an integer. Which error matters depends on the question.\n",
    "\n",
    "## Conditioning of a problem\n",
    "\n",
    "Before we ask whether an algorithm computes well, let us ask whether the problem can be computed\n",
    "well at all. The data almost always carry an error, if only a representation error of order $u$.\n",
    "If $\\hat x = x(1+\\delta)$ and $f$ is differentiable, then by Taylor’s formula\n",
    "\n",
    "$$\n",
    "f(\\hat x) = f(x) + f'(x)\\,x\\delta + O(\\delta^2)\n",
    "= f(x)\\Bigl(1 + \\frac{x f'(x)}{f(x)}\\,\\delta + O(\\delta^2)\\Bigr).\n",
    "$$\n",
    "\n",
    "```{admonition} Definition (condition number)\n",
    ":class: note\n",
    "Let $f$ be differentiable at the point $x$, with $f(x) \\neq 0$. The **condition number** of the\n",
    "problem of computing $f(x)$ is\n",
    "\n",
    "$$\n",
    "\\kappa_f(x) = \\left|\\frac{x\\,f'(x)}{f(x)}\\right| .\n",
    "$$\n",
    "\n",
    "A relative perturbation of the data by $\\delta$ changes the result, in relative terms, by about\n",
    "$\\kappa_f(x)\\,|\\delta|$. A problem with a large $\\kappa_f(x)$ is called **ill-conditioned**.\n",
    "```\n",
    "\n",
    "The condition number is a symbolic quantity, so let us compute it in SymPy for several functions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e8db8f85",
   "metadata": {},
   "outputs": [],
   "source": [
    "x, n = sp.symbols(\"x n\", positive=True)\n",
    "for f in (x - 1, sp.sqrt(x), sp.exp(x), x**n, sp.log(x), sp.sin(x)):\n",
    "    kappa = sp.simplify(x * sp.diff(f, x) / f)\n",
    "    print(f\"f(x) = {str(f):8}  kappa = |{kappa}|\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4ca08a4",
   "metadata": {},
   "source": [
    "The square root is always well conditioned ($\\kappa = \\tfrac12$): a perturbation of the data is\n",
    "halved. The power $x^{n}$ multiplies the relative error by $n$, and the exponential function by\n",
    "$|x|$. This explains the error we saw for Ramanujan’s constant: the argument $\\pi\\sqrt{163} \\approx 40.1$ was rounded with\n",
    "a relative error of order $u$, and $\\exp$ multiplied it by about $40$. The logarithm is\n",
    "ill-conditioned near $x = 1$, the sine near nonzero multiples of $\\pi$, and the subtraction\n",
    "$x \\mapsto x - 1$ near $x = 1$, where $\\kappa = |x/(x-1)|$ grows without bound.\n",
    "\n",
    "This last case is **catastrophic cancellation**. Let us compute $(1 + 10^{-15}) - 1$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "733748ba",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 1 + 1e-15                      # zapis 1 + 10**-15: jedno zaokrąglenie\n",
    "r = a - 1\n",
    "print(\"a - 1 =\", r, \"  odejmowanie dokładne:\", Fraction(a) - 1 == Fraction(r))\n",
    "X = 1 + Fraction(1, 10**15)        # dokładna liczba, którą chcieliśmy zapisać\n",
    "print(\"błąd względny zapisu a: \", float(abs(Fraction(a) - X) / X))\n",
    "print(\"kappa(x - 1) w punkcie X:\", float(X / (X - 1)))\n",
    "print(\"błąd względny wyniku:   \", float(abs(Fraction(r) - (X - 1)) / (X - 1)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f1d2aa7",
   "metadata": {},
   "source": [
    "The result differs from $10^{-15}$ by $11\\%$, even though the subtraction itself is exact (this is\n",
    "Sterbenz’s lemma). The error arose earlier, when the number $1 + 10^{-15}$ was stored: it is of\n",
    "order $10^{-16}$, that is, harmless. At this point, however, subtracting one has a condition number\n",
    "$\\kappa \\approx 10^{15}$ and amplifies this error to $10^{15} \\cdot 1.1\\cdot10^{-16} \\approx 0.11$ —\n",
    "just as the definition predicts. It is not the subtraction that spoils the result: it merely brings\n",
    "to the surface an error stored earlier in the data, and the large condition number tells us how\n",
    "many times this error will grow.\n",
    "\n",
    "## Stability of an algorithm\n",
    "\n",
    "Conditioning concerns the problem, not the way it is solved. The same problem can be computed by\n",
    "different algorithms, and each of them introduces its own rounding errors.\n",
    "\n",
    "```{admonition} Definition (backward stability)\n",
    ":class: note\n",
    "An algorithm $\\hat f$ for computing $f$ is **backward stable** if for all data $x$ its result is\n",
    "the exact value of $f$ for slightly perturbed data: $\\hat f(x) = f(\\hat x)$ for some $\\hat x$ with\n",
    "$|\\hat x - x| \\le C u\\,|x|$, where $C$ is a small constant that depends on the algorithm. Then the\n",
    "relative error of the result is approximately no larger than $\\kappa_f(x) \\cdot C u$.\n",
    "```\n",
    "\n",
    "A backward stable algorithm thus gives the exact answer to a slightly different question, and how\n",
    "much this answer differs from the true one is then decided by conditioning alone. A single\n",
    "IEEE 754 operation is backward stable: $\\fl(x+y) = x(1+\\delta) + y(1+\\delta)$ is the exact sum of\n",
    "numbers perturbed by the relative amount $\\delta$, $|\\delta| \\le u$. An **unstable** algorithm is\n",
    "usually one that solves an ill-conditioned subproblem along the way, even though the problem as\n",
    "a whole is well conditioned. Let us look at two examples.\n",
    "\n",
    "### The smaller root of a quadratic equation\n",
    "\n",
    "The equation $x^2 - bx + c = 0$ with a large $b > 0$ and $c = 1$ has two positive roots, close to\n",
    "$b$ and close to $c/b$. The schoolbook formula gives the smaller root as\n",
    "$\\bigl(b - \\sqrt{b^2 - 4c}\\bigr)/2$. Is the problem well conditioned? Let us compute in SymPy the\n",
    "condition number of the smaller root with respect to $b$ and with respect to $c$ for $b = 10^{8}$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1dae9667",
   "metadata": {},
   "outputs": [],
   "source": [
    "b, c = sp.symbols(\"b c\", positive=True)\n",
    "r = (b - sp.sqrt(b**2 - 4 * c)) / 2\n",
    "for zmienna in (b, c):\n",
    "    kappa = sp.simplify(zmienna * sp.diff(r, zmienna) / r)\n",
    "    print(f\"kappa względem {zmienna}: |{kappa}| =\",\n",
    "          sp.N(abs(kappa.subs({b: 10**8, c: 1})), 6))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c63c0f9",
   "metadata": {},
   "source": [
    "Both condition numbers equal $1$ to six digits: the problem is extremely well conditioned. Let us\n",
    "now compare the schoolbook formula with a second method, which first computes the larger root\n",
    "$x_1 = \\bigl(b + \\sqrt{b^2 - 4c}\\bigr)/2$ (without a subtraction) and then obtains the smaller one\n",
    "from Viète’s formula $x_1 x_2 = c$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0386a99b",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f\"{'b':>6} {'wzór szkolny':>22} {'bł. wzgl.':>9} \"\n",
    "      f\"{'Viète: c / x1':>22} {'bł. wzgl.':>9}\")\n",
    "for b_ in (1e4, 1e6, 1e8, 1e10):\n",
    "    c_ = 1.0\n",
    "    d = math.sqrt(b_ * b_ - 4 * c_)\n",
    "    szkolny = (b_ - d) / 2\n",
    "    viete = c_ / ((b_ + d) / 2)\n",
    "    B = mpmath.mpf(b_)\n",
    "    wzorzec = (B - mpmath.sqrt(B * B - 4)) / 2\n",
    "    bl = [float(abs(w - wzorzec) / wzorzec) for w in (szkolny, viete)]\n",
    "    print(f\"{b_:6.0e} {szkolny!r:>22} {bl[0]:9.1e} {viete!r:>22} {bl[1]:9.1e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd51c31c",
   "metadata": {},
   "source": [
    "For $b = 10^{8}$ the schoolbook formula is off by $25\\%$, and for $b = 10^{10}$ it gives zero.\n",
    "Viète’s formula has an error of order $u$ in all rows. The cause lies in the subtraction\n",
    "$b - \\sqrt{b^2-4c}$: the two numbers agree in almost all digits, and the computed square root\n",
    "$\\sqrt{b^2-4c}$ has an absolute error of order $u\\,b$. The subtraction is exact, but the result is\n",
    "of order $c/b$, so the relative error grows to about $u\\,b/(c/b) = u\\,b^2/c$, that is, for\n",
    "$b = 10^{8}$, to unity. The schoolbook formula is an unstable algorithm: it solves\n",
    "a well-conditioned problem through an ill-conditioned subtraction. Viète’s formula avoids\n",
    "subtracting nearby numbers.\n",
    "\n",
    "### The limit $(1 + 1/n)^n$\n",
    "\n",
    "The sequence $(1+1/n)^n$ tends to $e$. The natural algorithm first computes $y = 1 + 1/n$ and then\n",
    "$y^n$. The second step is a power with condition number $n$: the relative error $\\delta$ made when\n",
    "storing the number $y$ turns into a relative error of about $n\\delta$ in the result. We can compute\n",
    "the error $\\delta$ exactly with `Fraction`, so we can compare the prediction with reality. We\n",
    "compute the reference value of $(1+1/n)^n$ (not the limit $e$) in mpmath:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c41433eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f\"{'n':>6} {'delta zapisu y':>15} {'n * delta':>11}\"\n",
    "      f\" {'exp(n*delta) - 1':>17} {'błąd wyniku':>12}\")\n",
    "for k in (4, 8, 12, 14, 15):\n",
    "    n_ = 10.0**k\n",
    "    y = 1 + 1 / n_\n",
    "    dokladne_y = 1 + Fraction(1, 10**k)\n",
    "    delta = float((Fraction(y) - dokladne_y) / dokladne_y)\n",
    "    wzorzec = (1 + mpmath.mpf(1) / 10**k) ** (10**k)\n",
    "    blad = float((y**n_ - wzorzec) / wzorzec)\n",
    "    print(f\"{n_:6.0e} {delta:15.2e} {n_ * delta:11.2e}\"\n",
    "          f\" {math.expm1(n_ * delta):17.2e} {blad:12.2e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f00d6f9",
   "metadata": {},
   "source": [
    "The columns “$n \\cdot \\delta$” and `błąd wyniku` (“error of the result”) agree in sign and in the\n",
    "leading digits: the error of the naive algorithm comes entirely from rounding the number\n",
    "$1 + 1/n$, amplified $n$ times. More precisely,\n",
    "$\\bigl((1+1/n)(1+\\delta)\\bigr)^{n} = (1+1/n)^{n}(1+\\delta)^{n}$ and\n",
    "$(1+\\delta)^{n} \\approx e^{n\\delta}$. For $n = 10^{15}$ the linear approximation\n",
    "$e^{n\\delta} - 1 \\approx n\\delta$ is no longer sufficient, but the value $e^{n\\delta} - 1$ still\n",
    "agrees with the error of the result. The problem itself is well conditioned; it is the algorithm\n",
    "passing through the number $1 + 1/n$ that is unstable. A stable algorithm uses the formula\n",
    "$(1+1/n)^n = \\exp\\bigl(n\\log(1 + 1/n)\\bigr)$ and the function `math.log1p(t)`, which computes\n",
    "$\\log(1+t)$ with a relative error of order $u$ without forming the number $1 + t$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27e3f1a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f\"{'n':>5} {'naiwnie':>20} {'z log1p':>20} {'wzorzec':>20}\")\n",
    "for k in (8, 12, 15, 16):\n",
    "    n_ = 10.0**k\n",
    "    wzorzec = (1 + mpmath.mpf(1) / 10**k) ** (10**k)\n",
    "    naiwnie = (1 + 1 / n_) ** n_\n",
    "    z_log1p = math.exp(n_ * math.log1p(1 / n_))\n",
    "    print(f\"{n_:5.0e} {naiwnie!r:>20} {z_log1p!r:>20}\"\n",
    "          f\" {mpmath.nstr(wzorzec, 17):>20}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bb0ad0e",
   "metadata": {},
   "source": [
    "The version with `log1p` gives $16$–$17$ correct digits in all rows, while the naive one returns\n",
    "$1$ for $n = 10^{16}$, because $1 + 10^{-16}$ rounds to $1$. The deep dive,\n",
    "{doc}`part 2, §7 <../ieee754/i2_implementacja>`, shows a plot of the error of both versions for\n",
    "$n$ from $10$ to $10^{17}$, as well as the twin function `math.expm1`.\n",
    "\n",
    "## Summation\n",
    "\n",
    "A sum of $n$ numbers is the simplest computation with many operations. To bound its error, we need\n",
    "a lemma on products of factors $(1 + \\delta_i)$, which will also be useful in the last section.\n",
    "\n",
    "```{admonition} Lemma (product of relative errors)\n",
    ":class: important\n",
    "If $|\\delta_i| \\le u$ for $i = 1, \\dots, k$ and $ku < 1$, then\n",
    "$\\prod_{i=1}^{k}(1 + \\delta_i) = 1 + \\theta_k$, where\n",
    "\n",
    "$$\n",
    "|\\theta_k| \\le \\gamma_k := \\frac{ku}{1 - ku} .\n",
    "$$\n",
    "\n",
    "```\n",
    "\n",
    "*Proof.* The product lies between $(1-u)^{k}$ and $(1+u)^{k}$. By Bernoulli’s inequality,\n",
    "$(1-u)^{k} \\ge 1 - ku \\ge 1 - \\gamma_k$. From the inequality $e^{t} \\le 1/(1-t)$ for $0 \\le t < 1$\n",
    "we get $(1+u)^{k} \\le e^{ku} \\le 1/(1-ku) = 1 + \\gamma_k$. $\\blacksquare$\n",
    "\n",
    "```{admonition} Theorem (error of summation in a loop)\n",
    ":class: important\n",
    "Let $\\hat s$ be the sum of machine numbers $x_1, \\dots, x_n$ computed in the loop\n",
    "$\\hat s_1 = x_1$, $\\hat s_k = \\fl(\\hat s_{k-1} + x_k)$, without overflow or underflow, and let\n",
    "$(n-1)u < 1$. Then\n",
    "\n",
    "$$\n",
    "\\Bigl|\\hat s - \\sum_{i=1}^{n} x_i\\Bigr| \\le \\gamma_{n-1} \\sum_{i=1}^{n} |x_i|\n",
    "\\approx (n-1)\\,u \\sum_{i=1}^{n} |x_i| .\n",
    "$$\n",
    "\n",
    "```\n",
    "\n",
    "*Proof.* By the error model, $\\hat s_k = (\\hat s_{k-1} + x_k)(1 + \\delta_k)$, $|\\delta_k| \\le u$.\n",
    "Unrolling the recurrence, we get $\\hat s = \\sum_{i=1}^{n} x_i \\prod_{k=\\max(i,2)}^{n}(1+\\delta_k)$:\n",
    "each term passes through at most $n-1$ additions. By the lemma, each product has the form\n",
    "$1 + \\theta^{(i)}$ with $|\\theta^{(i)}| \\le \\gamma_{n-1}$, so\n",
    "$|\\hat s - \\sum x_i| = |\\sum x_i\\theta^{(i)}| \\le \\gamma_{n-1}\\sum|x_i|$. $\\blacksquare$\n",
    "(N. J. Higham, *Accuracy and Stability of Numerical Algorithms*, 2nd ed., SIAM 2002, ch. 4.)\n",
    "\n",
    "```{admonition} Pitfall: in Python 3.12, sum() is not a plain loop\n",
    ":class: warning\n",
    "Since Python 3.12, the built-in function `sum` adds `float` numbers with **error compensation**\n",
    "(Neumaier’s algorithm), so `sum([0.1] * 10) == 1.0` is true, while a `for` loop gives\n",
    "`0.9999999999999999`. To show the error of ordinary summation, you have to write the loop\n",
    "yourself. In older versions, `sum` was a plain loop.\n",
    "```\n",
    "\n",
    "Let us check the bound on the harmonic sum $H_n$ for $n = 10^{6}$, this time in the *binary64*\n",
    "format. We compare the forward and the backward loop, the built-in `sum`, the function `math.fsum`\n",
    "(which returns the correctly rounded exact sum of the given numbers), and `np.sum` (which sums\n",
    "pairwise, in a tree of additions):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a25e882f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def petla(xs):\n",
    "    s = 0.0\n",
    "    for x in xs:\n",
    "        s += x\n",
    "    return s\n",
    "\n",
    "n_ = 10**6\n",
    "wyrazy = [1 / k for k in range(1, n_ + 1)]\n",
    "H = mpmath.harmonic(n_)\n",
    "wyniki = {\"pętla w przód\": petla(wyrazy), \"pętla wstecz\": petla(wyrazy[::-1]),\n",
    "          \"sum()\": sum(wyrazy), \"math.fsum\": math.fsum(wyrazy),\n",
    "          \"np.sum\": float(np.sum(wyrazy))}\n",
    "for nazwa, s in wyniki.items():\n",
    "    blad = mpmath.mpf(s) - H\n",
    "    print(f\"{nazwa:14} {s!r:20}  błąd {mpmath.nstr(blad, 3):>10}\"\n",
    "          f\"  = {float(blad) / math.ulp(s):8.2f} ulp\")\n",
    "print(\"oszacowanie (n-1) u sum|x_i|:\", (n_ - 1) * 2**-53 * math.fsum(wyrazy))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2198c2b0",
   "metadata": {},
   "source": [
    "The forward loop is off by several hundred $\\ulp$, the backward loop by a few dozen, and `sum` and\n",
    "`math.fsum` by less than one. The error of $6.7\\cdot10^{-16}$ that remains in `math.fsum` does not\n",
    "come from the summation but from the data: each term $1/k$ was already rounded when it was stored.\n",
    "The bound from the theorem, $1.6\\cdot10^{-9}$, is true, but more than a thousand times too\n",
    "pessimistic: it describes the worst case, in which all the errors have the same sign and the\n",
    "largest possible magnitude. Compensated summation algorithms (Kahan’s, Neumaier’s, Shewchuk’s) and\n",
    "their guarantees are discussed in the deep dive, {doc}`part 2, §2 <../ieee754/i2_implementacja>`,\n",
    "and exercise C2 in {doc}`Lab 3 <../laboratoria/lab03_ieee754>` asks you to find data on which\n",
    "Neumaier’s method fails.\n",
    "\n",
    "## Muller’s sequence: when more digits do not help\n",
    "\n",
    "The last example shows a problem so ill-conditioned that no fixed precision is enough. Muller’s\n",
    "sequence is\n",
    "\n",
    "$$\n",
    "u_0 = 2, \\qquad u_1 = -4, \\qquad u_{n+1} = 111 - \\frac{1130}{u_n} + \\frac{3000}{u_n u_{n-1}} .\n",
    "$$\n",
    "\n",
    "We compute it in `float` and exactly, with fractions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c0e0c255",
   "metadata": {},
   "outputs": [],
   "source": [
    "def muller(u0, u1, n):\n",
    "    \"\"\"Wyraz u_n ciągu Mullera o wyrazach początkowych u0, u1.\"\"\"\n",
    "    a, b = u0, u1\n",
    "    for _ in range(n - 1):\n",
    "        a, b = b, 111 - 1130 / b + 3000 / (a * b)\n",
    "    return b\n",
    "\n",
    "for n_ in (5, 10, 15, 20, 30):\n",
    "    print(f\"n = {n_:2}:  float {muller(2.0, -4.0, n_)!r:20}\"\n",
    "          f\"  dokładnie {float(muller(Fraction(2), Fraction(-4), n_))!r}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12c919df",
   "metadata": {},
   "source": [
    "The exact terms tend to $6$, while the computation in `float` “jumps” to $100$ after a dozen or so\n",
    "steps and stays there for good. The explanation lies in the conditioning of the problem “compute\n",
    "$u_n$ from the data $u_0, u_1$.” Let us measure it in exact arithmetic: we perturb $u_1$ by\n",
    "$10^{-40}$ and check how much $u_n$ changes. The ratio of these relative changes approximates the\n",
    "condition number $\\kappa_n$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b93a8b17",
   "metadata": {},
   "outputs": [],
   "source": [
    "eps = Fraction(1, 10**40)\n",
    "for n_ in (5, 10, 15, 20, 25, 30):\n",
    "    un = muller(Fraction(2), Fraction(-4), n_)\n",
    "    zaburzony = muller(Fraction(2), Fraction(-4) + eps, n_)\n",
    "    kappa = abs((zaburzony - un) / un) / abs(eps / 4)\n",
    "    print(f\"n = {n_:2}:  kappa_n ≈ {float(kappa):.2e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f85257f",
   "metadata": {},
   "source": [
    "The condition number grows roughly $100/6 \\approx 16.7$ times per step. When $\\kappa_n u$ reaches\n",
    "one, that is, around $n = 15$, a rounding error of order $u$ is enough to destroy all the digits of\n",
    "the result — and that is exactly when the `float` result breaks away from $6$. Higher precision\n",
    "only shifts this moment: with $d$ digits, the disaster comes when $\\kappa_n$ reaches about\n",
    "$10^{d}$, and $\\kappa_n$ grows exponentially. In exercise D1 in\n",
    "{doc}`Lab 3 <../laboratoria/lab03_ieee754>` you will check how many steps you gain by adding\n",
    "digits. Exact computation works because the data $u_0 = 2$, $u_1 = -4$ are rational. The explicit\n",
    "formula for $u_n$, which reveals both limits, $6$ and $100$, is in the deep dive,\n",
    "{doc}`part 2, §7 <../ieee754/i2_implementacja>`.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* The relative error is the natural measure in floating-point arithmetic; which error matters is\n",
    "  decided by the question.\n",
    "* The condition number $\\kappa_f(x) = |xf'(x)/f(x)|$ tells us how many times the problem amplifies\n",
    "  the relative error of the data. Subtracting nearby numbers is ill-conditioned: it reveals errors\n",
    "  in the data, even though it is itself exact.\n",
    "* A backward stable algorithm gives the exact result for slightly perturbed data, so its error is\n",
    "  about $\\kappa \\cdot Cu$. An unstable algorithm passes through an ill-conditioned subproblem: the\n",
    "  schoolbook formula for the roots, $(1+1/n)^n$ computed directly.\n",
    "* The error of summation in a loop does not exceed $\\gamma_{n-1}\\sum|x_i|$; in practice it is much\n",
    "  smaller. In Python 3.12, `sum` of `float` numbers uses compensation, and `math.fsum` rounds the\n",
    "  exact sum.\n",
    "* For an ill-conditioned problem, such as Muller’s sequence, more digits only postpone the\n",
    "  disaster. What helps is exact computation or mathematical analysis.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. ★ The number $\\pi$ has the approximations $3.14$ and $\\tfrac{22}{7}$. Compute the absolute and\n",
    "   relative errors of both, as well as the number of correct significant digits. Which\n",
    "   approximation is better?\n",
    "2. ★ Compute in SymPy the condition numbers of the functions $f(x) = x^2 - 1$ and $g(x) = \\cos x$.\n",
    "   Where are these problems ill-conditioned?\n",
    "3. ★★ For $x = 1 + 10^{-8}$, compare the results of `x*x - 1` and `(x - 1)*(x + 1)` with the exact\n",
    "   value (`Fraction`). Which algorithm is stable, and why? Point out an operation in it that is\n",
    "   exact by Sterbenz’s lemma.\n",
    "4. ★★ The integrals $I_n = \\int_0^1 x^{n} e^{x-1}\\,dx$ satisfy $I_0 = 1 - 1/e$ and\n",
    "   $I_n = 1 - nI_{n-1}$. Compute $I_{20}$ with this recurrence in `float`, and then with the\n",
    "   backward recurrence $I_{n-1} = (1 - I_n)/n$, starting from $I_{40} = 0$. Compare with the value\n",
    "   from `mpmath.quad` and explain the result by tracking how the error changes in one step of each\n",
    "   recurrence.\n",
    "5. ★★★ Show that, up to terms of order $u^2$, the error of summation in a loop satisfies\n",
    "   $|\\hat s - s| \\lesssim u\\sum_{k=2}^{n}|\\hat s_k|$, where $\\hat s_k$ are the computed partial\n",
    "   sums. Use this bound to explain why the harmonic sum computed backward is more accurate.\n",
    "6. ★★★ The substitution $u_n = y_{n+1}/y_n$ turns Muller’s recurrence into the linear recurrence\n",
    "   $y_{n+1} = 111y_n - 1130y_{n-1} + 3000y_{n-2}$. Find its general solution in SymPy, fit the\n",
    "   constants to $u_0 = 2$, $u_1 = -4$, and show that the coefficient of $100^{n}$ is zero. What\n",
    "   happens to this coefficient when $u_1$ is perturbed by $\\varepsilon \\neq 0$?"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
