{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "08bd2dbf",
   "metadata": {},
   "source": [
    "# Part 2. Implementation: tricks and subtleties\n",
    "\n",
    "The standard says *what* the result must be. This part shows what that looks like in practice: in\n",
    "the bits, in the compiler, in Python, and in math libraries — and which tricks follow from it.\n",
    "\n",
    "In §1 we read the bits of a number as an integer and derive the fast inverse square root from\n",
    "this. In §2 we show that the rounding error of an addition or a multiplication is itself a machine\n",
    "number, and we build compensated summation algorithms on this fact. In §3 we turn to the FMA\n",
    "operation, in §4 to situations in which the same program gives different results, in §5 to how\n",
    "Python handles exceptions, NaN, negative zero, and the printing of numbers, and in §6 to the\n",
    "elementary functions, on which the standard imposes no binding requirements. In §7 we collect\n",
    "formulas that are robust to rounding, and §8 gives a brief history. The first cell defines helper\n",
    "functions: `bity` and `z_bitow` convert between a `float` and its 64 bits, and `losowa` draws\n",
    "random numbers from a wide range of magnitudes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f4945670",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math, platform, random, shutil, statistics, struct, subprocess, tempfile, warnings\n",
    "from fractions import Fraction\n",
    "from pathlib import Path\n",
    "import mpmath\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "random.seed(754)\n",
    "\n",
    "def bity(x):\n",
    "    \"\"\"64 bity liczby float odczytane jako liczba całkowita bez znaku.\"\"\"\n",
    "    return struct.unpack('<Q', struct.pack('<d', x))[0]\n",
    "\n",
    "def z_bitow(n):\n",
    "    \"\"\"Liczba float o podanych 64 bitach.\"\"\"\n",
    "    return struct.unpack('<d', struct.pack('<Q', n))[0]\n",
    "\n",
    "def losowa(zakres=40):\n",
    "    \"\"\"Losowa liczba float: mantysa z [1, 2), wykładnik od -zakres do zakres, losowy znak.\"\"\"\n",
    "    return random.uniform(1, 2) * 2.0**random.randint(-zakres, zakres) * random.choice((1, -1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "377136fa",
   "metadata": {},
   "source": [
    "## 1. Bits as an integer\n",
    "\n",
    "In Part 1 we saw that for the zero $+0$ and the positive numbers, the order of the numbers is the\n",
    "order of their bits. Some simple tricks follow from this.\n",
    "\n",
    "### The next number is “+1”, and 0.1 + 0.2 is the neighbor of 0.3\n",
    "\n",
    "Since the order of the numbers is the order of their bits, the next machine number after\n",
    "a positive number $x$ is obtained by adding $1$ to its bits. The distance between two numbers of\n",
    "the same sign, measured in ulps, is simply the difference of their bits:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91aaa9c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"z_bitow(bity(1.0) + 1) =\", z_bitow(bity(1.0) + 1), \"= nextafter(1, 2):\",\n",
    "      z_bitow(bity(1.0) + 1) == math.nextafter(1.0, 2.0))\n",
    "print(\"odległość 0.1 + 0.2 od 0.3:\", bity(0.1 + 0.2) - bity(0.3), \"ulp\")\n",
    "print(\"sąsiedzi 0.3:\", math.nextafter(0.3, 0), \"|\", 0.3, \"|\", math.nextafter(0.3, 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44a3b7ad",
   "metadata": {},
   "source": [
    "`0.1 + 0.2` is not just “some” wrong number: it is the next machine number after `0.3`. The test\n",
    "suites of numerical libraries measure the agreement of results in exactly this way — in ulps, that\n",
    "is, by the difference of the bit patterns.\n",
    "\n",
    "### The bits are almost a logarithm\n",
    "\n",
    "If $x=2^E(1+m)$ with $0\\le m<1$ is a positive normal number, then the bits of $x$ are\n",
    "$2^{52}(E+1023)+2^{52}m$, so\n",
    "\n",
    "$$\n",
    "\\frac{\\texttt{bity}(x)}{2^{52}}-1023=E+m\\approx E+\\log_2(1+m)=\\log_2x .\n",
    "$$\n",
    "\n",
    "Reading the bits as an integer gives a piecewise linear approximation of the base-2 logarithm.\n",
    "The largest error is $\\max_{0\\le m<1}\\bigl(\\log_2(1+m)-m\\bigr)\\approx0.0861$, attained at\n",
    "$m=1/\\ln2-1$. Let us plot $\\log_2x$ and the rescaled bits for $x\\in[1/16,16]$ and compare the\n",
    "largest measured difference with this value:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2335e89c",
   "metadata": {},
   "outputs": [],
   "source": [
    "xs = np.geomspace(1 / 16, 16, 4000)\n",
    "przyblizenie = np.array([bity(float(x)) / 2**52 - 1023 for x in xs])\n",
    "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.2))\n",
    "ax1.plot(xs, np.log2(xs), lw=2, label=r\"$\\log_2 x$\")\n",
    "ax1.plot(xs, przyblizenie, lw=1.2, ls=\"--\", label=r\"$\\mathtt{bity}(x)/2^{52}-1023$\")\n",
    "ax1.legend()\n",
    "ax2.plot(xs, np.log2(xs) - przyblizenie, color=\"C2\")\n",
    "ax2.set_title(\"różnica\", fontsize=10)\n",
    "for ax in (ax1, ax2):\n",
    "    ax.set_xscale(\"log\", base=2)\n",
    "    ax.set_xlabel(\"$x$\")\n",
    "    ax.grid(alpha=0.3)\n",
    "fig.tight_layout()\n",
    "plt.show()\n",
    "m = 1 / math.log(2) - 1\n",
    "print(\"największa różnica na wykresie:\", max(np.log2(xs) - przyblizenie),\n",
    "      \"  teoretycznie:\", math.log2(1 + m) - m)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9753bd92",
   "metadata": {},
   "source": [
    "The largest measured difference agrees with the theoretical value $0.0861$. At powers of two\n",
    "($m=0$) the approximation is exact, and the largest error occurs roughly in the middle of each\n",
    "interval $[2^E,2^{E+1})$.\n",
    "\n",
    "### Fast inverse square root (Quake III Arena, 1999)\n",
    "\n",
    "Since the bits are almost a logarithm, $\\log_2(1/\\sqrt x)=-\\tfrac12\\log_2x$ translates into the\n",
    "bits: $i_y\\approx K-i_x/2$ for a suitable constant $K$, where $i_x$ and $i_y$ are the bits of $x$\n",
    "and of $y\\approx1/\\sqrt x$ read as integers (here 32-bit ones). The game Quake III Arena\n",
    "(id Software, 1999; the source code was released in 2005) computed $1/\\sqrt x$ this way when\n",
    "normalizing vectors for graphics: in the binary32 format, with the constant `0x5f3759df` and one\n",
    "step of Newton’s method for $f(y)=1/y^2-x$. Here the Newton step $y\\leftarrow y-f(y)/f'(y)$ takes\n",
    "a division-free form:\n",
    "\n",
    "$$\n",
    "y \\leftarrow y-\\frac{y^{-2}-x}{-2y^{-3}} = y\\Bigl(\\frac32-\\frac{x}{2}\\,y^2\\Bigr).\n",
    "$$\n",
    "\n",
    "If $y=(1+e)/\\sqrt x$, then after the step the relative error is $-\\tfrac32e^2-\\tfrac12e^3$ —\n",
    "Newton’s method converges quadratically. Let us see how this works for the number $2$ and on the\n",
    "whole interval $[1,4)$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aab30d00",
   "metadata": {},
   "outputs": [],
   "source": [
    "def odwrotny_pierwiastek(x, kroki_newtona=1):\n",
    "    \"\"\"1/√x sztuczką z Quake III (binary32).\"\"\"\n",
    "    x = np.float32(x)\n",
    "    i = np.array([x]).view(np.int32)[0]            # bity liczby x jako int32\n",
    "    i = np.int32(0x5f3759df - (int(i) >> 1))       # „połowa logarytmu” ze zmienionym znakiem\n",
    "    y = np.array([i]).view(np.float32)[0]          # te same bity jako float32\n",
    "    for _ in range(kroki_newtona):\n",
    "        y = y * (np.float32(1.5) - np.float32(0.5) * x * y * y)\n",
    "    return y\n",
    "\n",
    "print(\"x = 2:\", odwrotny_pierwiastek(2.0, 0), \"→ po kroku Newtona\", odwrotny_pierwiastek(2.0),\n",
    "      \"  dokładnie:\", 1 / math.sqrt(2))\n",
    "siatka = np.linspace(1, 4, 30001)    # wystarczy [1, 4): x·4 daje dokładnie wynik / 2\n",
    "for kroki in (0, 1, 2):\n",
    "    blad = max(abs(float(odwrotny_pierwiastek(v, kroki)) * math.sqrt(v) - 1) for v in siatka)\n",
    "    print(f\"kroki Newtona: {kroki}   największy błąd względny: {blad:.4%}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70deb4a7",
   "metadata": {},
   "source": [
    "After one Newton step the error does not exceed $0.18\\%$ — more than enough for graphics, and with\n",
    "no division and no square root. The numbers agree with the convergence analysis:\n",
    "$\\tfrac32\\cdot(3.44\\%)^2\\approx0.18\\%$, and $\\tfrac32\\cdot(0.18\\%)^2\\approx0.0005\\%$. An analysis\n",
    "of the constant was given by C. Lomont (2003); today processors have dedicated instructions for\n",
    "this. In the original, the bits were read through a pointer cast, which in C is formally undefined\n",
    "behavior; in Python we use a NumPy array view (`view`).\n",
    "\n",
    "## 2. The rounding error is a machine number\n",
    "\n",
    "So far we have only estimated the rounding error. It turns out, however, that the error of\n",
    "a single addition or multiplication is itself a machine number and can be computed exactly with\n",
    "ordinary operations. Double-length arithmetic and compensated summation rest on this fact.\n",
    "\n",
    "### TwoSum: the exact error of addition\n",
    "\n",
    "```{admonition} Theorem (Møller 1965, Knuth 1969)\n",
    ":class: important\n",
    "If we round to nearest, then for machine numbers $a,b$ (barring overflow) the six operations of\n",
    "the function `two_sum` yield $s=\\fl(a+b)$ and a machine number $e$ such that $a+b=s+e$ **exactly**.\n",
    "```\n",
    "\n",
    "The theorem says two things. First, with rounding to nearest, the error of an addition,\n",
    "$a+b-\\fl(a+b)$, is always a **machine number** — no extra precision is needed to store it.\n",
    "Second, this error can be computed with ordinary operations. In the code, `bb = s - a` is the part\n",
    "of $b$ that “made it” into the sum, `s - bb` is the part of $a$ that made it into the sum, and the\n",
    "two differences in the last line are what was lost from $a$ and from $b$. The proof that all the\n",
    "operations except the first are exact relies on Sterbenz’s lemma (Knuth, TAOCP, vol. 2, §4.2.2).\n",
    "When it is known that $|a|\\ge|b|$, three operations suffice (Dekker’s FastTwoSum).\n",
    "\n",
    "Let us test the theorem on $50{,}000$ random pairs and on two well-known examples:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6e3f84fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "def two_sum(a, b):\n",
    "    s = a + b\n",
    "    bb = s - a\n",
    "    e = (a - (s - bb)) + (b - bb)\n",
    "    return s, e\n",
    "\n",
    "zle = sum(Fraction(a) + Fraction(b) != sum(map(Fraction, two_sum(a, b)))\n",
    "          for a, b in ((losowa(), losowa()) for _ in range(50_000)))\n",
    "print(\"niedokładnych rozkładów na 50 000:\", zle)\n",
    "print(\"two_sum(0.1, 0.2) =\", two_sum(0.1, 0.2))\n",
    "print(\"two_sum(1e16, 1.0) =\", two_sum(1e16, 1.0))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1599bee",
   "metadata": {},
   "source": [
    "The error of the addition $0.1+0.2$ is exactly $-2^{-55}\\approx-2.78\\cdot10^{-17}$. In\n",
    "$10^{16}+1$ the whole 1 was lost — and `two_sum` recovers it.\n",
    "\n",
    "### TwoProduct: the exact error of multiplication\n",
    "\n",
    "A product also splits exactly: $a\\cdot b=p+e$, where $p=\\fl(ab)$ and $e$ is a machine number\n",
    "(provided there is no underflow). Without hardware FMA this is done by Dekker’s method (1971).\n",
    "Veltkamp’s splitting writes each number as a sum $a=a_h+a_l$ in which both parts have at most $26$\n",
    "significant bits. The product of two such parts has at most $52$ bits, so it fits into the\n",
    "$53$-bit significand and is computed **exactly**; from the four exact partial products we assemble\n",
    "the error $e$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee6a4345",
   "metadata": {},
   "outputs": [],
   "source": [
    "C = 2.0**27 + 1          # 134217729\n",
    "\n",
    "def rozszczep(a):\n",
    "    t = C * a\n",
    "    hi = t - (t - a)\n",
    "    return hi, a - hi\n",
    "\n",
    "def two_prod(a, b):\n",
    "    p = a * b\n",
    "    ah, al = rozszczep(a)\n",
    "    bh, bl = rozszczep(b)\n",
    "    e = ((ah * bh - p) + ah * bl + al * bh) + al * bl\n",
    "    return p, e\n",
    "\n",
    "zle = sum(Fraction(a) * Fraction(b) != sum(map(Fraction, two_prod(a, b)))\n",
    "          for a, b in ((losowa(), losowa()) for _ in range(50_000)))\n",
    "print(\"niedokładnych rozkładów na 50 000:\", zle, \"  two_prod(0.1, 0.1) =\", two_prod(0.1, 0.1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7ec525f",
   "metadata": {},
   "source": [
    "All $50{,}000$ decompositions are exact, and the error of the product $0.1\\cdot0.1$ is about\n",
    "$-8.33\\cdot10^{-19}$ (in §3 we will compute it with a single FMA operation). From such pairs of\n",
    "numbers one builds “double-length” arithmetic (*double-double*): a pair $(p,e)$ with\n",
    "$|e|\\le\\tfrac12\\ulp(p)$ represents the number $p+e$ with a precision of about $2\\cdot53=106$ bits,\n",
    "without any special hardware.\n",
    "\n",
    "### Compensated summation\n",
    "\n",
    "A sum of $n$ numbers can be computed in several ways, which come with different guarantees\n",
    "(N. J. Higham, *Accuracy and Stability of Numerical Algorithms*, Chapter 4). Neglecting terms of\n",
    "higher order in $u$ (we assume that $nu\\ll1$), the bounds on the absolute error are as follows:\n",
    "\n",
    "* the plain loop has an error of at most $(n-1)\\,u\\sum_i|x_i|$;\n",
    "* pairwise summation (a tree of additions), at most about $u\\log_2 n\\sum_i|x_i|$;\n",
    "* Kahan’s compensated summation, at most $2u\\sum_i|x_i|$, independently of $n$.\n",
    "\n",
    "The functions below implement the loop and the methods of Kahan and Neumaier; we compare them with\n",
    "the ready-made `sum`, `np.sum`, and `math.fsum` on a sum in which the plain loop loses all the\n",
    "small terms:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "967c01fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "def petla(xs):\n",
    "    s = 0.0\n",
    "    for x in xs:\n",
    "        s += x\n",
    "    return s\n",
    "\n",
    "def kahan(xs):\n",
    "    s = c = 0.0                      # c: utracona część poprzednich dodawań\n",
    "    for x in xs:\n",
    "        y = x - c\n",
    "        t = s + y\n",
    "        c = (t - s) - y\n",
    "        s = t\n",
    "    return s\n",
    "\n",
    "def neumaier(xs):\n",
    "    s = c = 0.0\n",
    "    for x in xs:\n",
    "        t = s + x\n",
    "        c += (s - t) + x if abs(s) >= abs(x) else (x - t) + s\n",
    "        s = t\n",
    "    return s + c\n",
    "\n",
    "def porownaj(xs, dokladnie):\n",
    "    for nazwa, f in ((\"pętla\", petla), (\"Kahan\", kahan), (\"Neumaier\", neumaier),\n",
    "                     (\"sum()\", sum), (\"np.sum\", np.sum), (\"math.fsum\", math.fsum)):\n",
    "        w = float(f(xs))\n",
    "        print(f\"{nazwa:10} {w!r:24} błąd: {Fraction(w) - dokladnie}\")\n",
    "\n",
    "porownaj([1e16] + [1.0] * 1000, Fraction(10**16 + 1000))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd03d04a",
   "metadata": {},
   "source": [
    "The plain loop (`petla`) loses every single 1: $\\ulp(10^{16})=2$, and $10^{16}+1$ is a tie,\n",
    "broken to even, that is, to $10^{16}$. Kahan (1965) carries the lost part $c$ over to the next\n",
    "step. NumPy sums pairwise, so the error grows like $\\log n$ rather than like $n$ — here it loses\n",
    "$12$. Since Python 3.12, `sum` uses Neumaier’s method\n",
    "({doc}`Lecture 1, §1.4 <../wyklady/w01_4_obliczenie_sprawdzenie_dowod>`),\n",
    "and `math.fsum` (Shewchuk’s algorithm) returns the correctly rounded exact sum. How does Neumaier’s\n",
    "method differ from Kahan’s? This is best seen on a sum in which a term much larger than the\n",
    "running sum appears:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75e2ad75",
   "metadata": {},
   "outputs": [],
   "source": [
    "porownaj([1.0, 1e100, 1.0, -1e100], Fraction(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e8d0974",
   "metadata": {},
   "source": [
    "Kahan’s method assumes that the running sum is larger in absolute value than the number being\n",
    "added. When a number larger than the sum arrives ($10^{100}$), the correction is lost.\n",
    "Neumaier (1974) handles both cases — and it is his version that Python’s `sum` uses. Pairwise\n",
    "summation does not help: `np.sum` also gives $0$, because both ones are lost before $10^{100}$ and\n",
    "$-10^{100}$ cancel.\n",
    "\n",
    "## 3. FMA: one rounding instead of two\n",
    "\n",
    "The FMA operation (*fused multiply-add*, in the standard since 2008) computes $\\fl(a\\cdot b+c)$\n",
    "with a **single** rounding. Almost all modern processors have it; Python has had `math.fma` since\n",
    "version 3.13. Here we emulate it exactly with rational arithmetic:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7cf7e3e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "def fma(a, b, c):\n",
    "    \"\"\"fl(a*b + c) z jednym zaokrągleniem.\"\"\"\n",
    "    return float(Fraction(a) * Fraction(b) + Fraction(c))\n",
    "\n",
    "print(\"0.1*10 - 1 =\", 0.1 * 10 - 1, \"   fma(0.1, 10, -1) =\", fma(0.1, 10.0, -1.0),\n",
    "      \"= 2**-54:\", fma(0.1, 10.0, -1.0) == 2.0**-54)\n",
    "p = 0.1 * 0.1\n",
    "print(\"błąd iloczynu 0,1·0,1:  fma →\", fma(0.1, 0.1, -p), \"  two_prod →\", two_prod(0.1, 0.1)[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4854cf55",
   "metadata": {},
   "source": [
    "The exact product of the machine number `0.1` and $10$ is $1+2^{-54}$, which rounds to exactly\n",
    "$1$, so ordinary operations hide the error; FMA reveals it: $2^{-54}$. With FMA, the exact error of\n",
    "a product takes a single instruction, $e=\\mathrm{fma}(a,b,-p)$; the second line of the output\n",
    "shows that it gives the same result as `two_prod` from §2.\n",
    "\n",
    "### The compiler fuses operations: $\\sqrt{a\\cdot a-a\\cdot a}=\\mathrm{NaN}$\n",
    "\n",
    "The C standard allows the compiler to replace $a\\cdot b+c$ within a single expression by an FMA\n",
    "(`FP_CONTRACT`). Clang does so by default (`-ffp-contract=on`), GCC even more boldly\n",
    "(`-ffp-contract=fast`). Then `a*a - a*a` is computed as\n",
    "$\\mathrm{fma}\\bigl(a,a,-\\fl(a\\cdot a)\\bigr)$, that is, as the rounding error of the product, not\n",
    "as zero:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c487ed91",
   "metadata": {},
   "outputs": [],
   "source": [
    "for a in (0.1, 0.3, 0.7):\n",
    "    e = fma(a, a, -(a * a))\n",
    "    print(f\"a = {a}:  a*a - a*a z FMA = {e!r:>24}   sqrt: {math.sqrt(e) if e >= 0 else 'NaN'}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d2174e4",
   "metadata": {},
   "source": [
    "For $a=0.1$ and $a=0.3$ the error of the product is negative, so there is a negative number under\n",
    "the square root, and the result is NaN; for $a=0.7$ the error is positive, and instead of zero we\n",
    "get about $1.5\\cdot10^{-9}$. Let us now run a real C program, compiled twice: with the default\n",
    "settings and with operation fusing turned off (the cell runs the `clang` compiler if it is\n",
    "available on the system). The program receives $a=0.1$ only at run time (`atof(argv[1])`), so\n",
    "that the compiler cannot compute the result in advance:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afea22dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "def uruchom_c(zrodlo, flagi, *argumenty, przedrostek=()):\n",
    "    \"\"\"Kompiluje program w C (clang) i uruchamia go; zwraca wypisany tekst.\"\"\"\n",
    "    if shutil.which(\"clang\") is None:\n",
    "        return \"(brak kompilatora clang)\"\n",
    "    with tempfile.TemporaryDirectory() as kat:\n",
    "        plik, exe = Path(kat) / \"p.c\", Path(kat) / \"p\"\n",
    "        plik.write_text(zrodlo)\n",
    "        kompilacja = subprocess.run([\"clang\", \"-O2\", *flagi, str(plik), \"-o\", str(exe), \"-lm\"],\n",
    "                                    capture_output=True, text=True)\n",
    "        if kompilacja.returncode != 0:\n",
    "            return \"(nie udało się skompilować)\"\n",
    "        try:\n",
    "            wynik = subprocess.run([*przedrostek, str(exe), *argumenty],\n",
    "                                   capture_output=True, text=True, timeout=30)\n",
    "        except OSError:\n",
    "            return \"(nie udało się uruchomić)\"\n",
    "        return wynik.stdout.strip() or \"(nie udało się uruchomić)\"\n",
    "\n",
    "PROGRAM_FMA = r\"\"\"\n",
    "#include <stdio.h>\n",
    "#include <stdlib.h>\n",
    "#include <math.h>\n",
    "int main(int argc, char **argv) {\n",
    "    double a = atof(argv[1]);           /* a = 0.1 podane w czasie działania */\n",
    "    double d = a * a - a * a;\n",
    "    printf(\"a*a - a*a = %g,  sqrt = %g\\n\", d, sqrt(d));\n",
    "    return 0;\n",
    "}\n",
    "\"\"\"\n",
    "print(\"procesor:\", platform.machine())\n",
    "for flagi in ([], [\"-ffp-contract=off\"]):\n",
    "    opis = \" \".join(flagi) or \"(ustawienia domyślne)\"\n",
    "    print(f\"clang {opis:22}\", uruchom_c(PROGRAM_FMA, flagi, \"0.1\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1744b54c",
   "metadata": {},
   "source": [
    "On a processor with an FMA instruction (e.g., ARM), the result depends on the compiler flag: with\n",
    "the default settings the square root of “zero” is NaN. An expression that is mathematically\n",
    "identically zero depends, in practice, on the compiler.\n",
    "\n",
    "## 4. Same program, different results\n",
    "\n",
    "The rule from Part 1 guarantees the same bits only when the program performs the same operations\n",
    "in the same format. In practice this condition is easy to violate: intermediate results are\n",
    "sometimes stored in a different precision, and for some operations the standard does not specify\n",
    "the outcome at all. Here are three such situations.\n",
    "\n",
    "### Double rounding\n",
    "\n",
    "The x87 coprocessor (x86 processors before SSE2 became widespread) computed in 80-bit registers\n",
    "with a 64-bit significand and rounded to binary64 only when storing to memory. Two roundings are\n",
    "not the same as one. To show this, we need a reference rounding to an arbitrary number of bits.\n",
    "The function `zaokraglij(q, p)` determines the exponent $e$ from the condition\n",
    "$2^e\\le q<2^{e+1}$, scales $q$ to the interval $[2^{p-1},2^p)$, divides it by $1$ with remainder,\n",
    "and breaks ties to even — exactly as the standard prescribes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "472e1dc1",
   "metadata": {},
   "outputs": [],
   "source": [
    "def zaokraglij(q, p):\n",
    "    \"\"\"Fraction q > 0 zaokrąglona do p bitów mantysy (do najbliższej, remis do parzystej).\"\"\"\n",
    "    e = q.numerator.bit_length() - q.denominator.bit_length()\n",
    "    if Fraction(2)**e > q:\n",
    "        e -= 1                                     # teraz 2**e <= q < 2**(e + 1)\n",
    "    skala = Fraction(2)**(p - 1 - e)\n",
    "    n, r = divmod(q * skala, 1)\n",
    "    if r > Fraction(1, 2) or (r == Fraction(1, 2) and n % 2 == 1):\n",
    "        n += 1\n",
    "    return n / skala\n",
    "\n",
    "b = 2.0**-53 + 2.0**-70                             # liczba maszynowa\n",
    "dokladnie = 1 + Fraction(b)\n",
    "print(\"jedno zaokrąglenie (53 bity):     \", float(zaokraglij(dokladnie, 53)), \"  Python:\", 1 + b)\n",
    "print(\"najpierw do 64 bitów, potem do 53:\", float(zaokraglij(zaokraglij(dokladnie, 64), 53)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2f9fa98",
   "metadata": {},
   "source": [
    "$1+b$ lies just above the midpoint between $1$ and $1+2^{-52}$, so the correct result is\n",
    "$1+2^{-52}$. Rounding to 64 bits loses $2^{-70}$ and turns the number into an exact tie, which the\n",
    "second rounding breaks to even — downward, to $1$. Modern processors (x86-64 with SSE2, ARM)\n",
    "compute in binary64 directly, but old 32-bit code and mixed precision still produce such\n",
    "discrepancies (Monniaux 2008).\n",
    "\n",
    "### float32 in the middle of a computation\n",
    "\n",
    "The second source of discrepancies is mixed precision. A number stored once in the binary32 format\n",
    "and then carried over to binary64 retains the binary32 rounding error — of relative order\n",
    "$2^{-24}$, not $2^{-53}$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f373d3b",
   "metadata": {},
   "outputs": [],
   "source": [
    "x32 = np.float32(0.1)\n",
    "print(\"float32:\", x32, \"  → z powrotem jako float64:\", float(x32),\n",
    "      \"  równe 0.1?\", float(x32) == 0.1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1163882e",
   "metadata": {},
   "source": [
    "Graphics cards and machine-learning libraries often compute in binary32 or bfloat16. The number\n",
    "“0.1” stored once in binary32 and read back as float64 is $0.10000000149011612$. In binary32 it\n",
    "looks innocent (`0.1`), because that is its shortest representation in that format — which is why\n",
    "such an error in a data pipeline is easy to miss.\n",
    "\n",
    "### NaN converted to an integer\n",
    "\n",
    "When NaN or a number that is too large is converted to an integer, the standard requires the\n",
    "*invalid* exception to be signaled, but it does not say which integer to return; in C this is\n",
    "undefined behavior. Processors handle it differently (the x86-64 version runs on Apple computers\n",
    "with ARM processors thanks to the Rosetta 2 translation layer):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "efc42edd",
   "metadata": {},
   "outputs": [],
   "source": [
    "PROGRAM_NAN = r\"\"\"\n",
    "#include <stdio.h>\n",
    "#include <stdlib.h>\n",
    "#include <math.h>\n",
    "int main(int argc, char **argv) {\n",
    "    volatile double nan_ = NAN * atof(argv[1]), duza = 1e300;\n",
    "    printf(\"(long long)NaN = %lld,  (long long)1e300 = %lld\\n\",\n",
    "           (long long)nan_, (long long)duza);\n",
    "    return 0;\n",
    "}\n",
    "\"\"\"\n",
    "print(\"ARM64: \", uruchom_c(PROGRAM_NAN, [\"-arch\", \"arm64\"], \"1\"))\n",
    "print(\"x86-64:\", uruchom_c(PROGRAM_NAN, [\"-arch\", \"x86_64\"], \"1\",\n",
    "                           przedrostek=[\"arch\", \"-x86_64\"]))\n",
    "with warnings.catch_warnings():\n",
    "    warnings.simplefilter(\"ignore\")\n",
    "    print(\"NumPy na tym komputerze:\", np.array([np.nan, 1e300]).astype(np.int64))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50dc1897",
   "metadata": {},
   "source": [
    "For every invalid argument, x86-64 processors return the “integer indefinite” value $-2^{63}$;\n",
    "ARM64 saturates the result to the representable range and converts NaN to $0$. So the same program\n",
    "gives different numbers on different computers. NumPy converts numbers the same way as the C\n",
    "program, so on this computer (ARM64) it gives the same results.\n",
    "\n",
    "```{admonition} The conversion that destroyed a rocket\n",
    ":class: warning\n",
    "On June 4, 1996, 37 seconds after engine ignition, the Ariane 5 rocket (Flight 501) lost control\n",
    "and was destroyed. The software of the inertial reference system converted a 64-bit floating-point\n",
    "number (the quantity BH, *horizontal bias*, related to the horizontal velocity) into a 16-bit\n",
    "signed integer. The value exceeded 32,767, the conversion was not protected, and the resulting\n",
    "exception shut down both inertial reference systems (report of the Inquiry Board chaired by\n",
    "J. L. Lions, ESA 1996).\n",
    "```\n",
    "\n",
    "## 5. Python and the standard\n",
    "\n",
    "Python computes with binary64 numbers using the processor’s hardware operations, so the results of\n",
    "individual operations conform to the standard. It does, however, have its own rules for handling\n",
    "exceptional situations, for comparisons with NaN, for printing negative zero, and for converting\n",
    "numbers to text.\n",
    "\n",
    "### Exceptions instead of special values\n",
    "\n",
    "According to the standard, computations do not stop by default: the result receives a special\n",
    "value, and the processor raises a flag (Part 1, §4). Python chose otherwise and in many cases\n",
    "raises an exception. Let us compare it with NumPy on the same expressions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "132a49d6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def sprobuj(f):\n",
    "    try:\n",
    "        return str(f())\n",
    "    except Exception as e:\n",
    "        return type(e).__name__\n",
    "\n",
    "PRZYPADKI = [\n",
    "    (\"1.0 / 0.0\", lambda: 1.0 / 0.0, lambda: np.float64(1.0) / 0.0),\n",
    "    (\"0.0 / 0.0\", lambda: 0.0 / 0.0, lambda: np.float64(0.0) / 0.0),\n",
    "    (\"math.sqrt(-1.0)\", lambda: math.sqrt(-1.0), lambda: np.sqrt(np.float64(-1.0))),\n",
    "    (\"math.log(0.0)\", lambda: math.log(0.0), lambda: np.log(np.float64(0.0))),\n",
    "    (\"math.exp(1000.0)\", lambda: math.exp(1000.0), lambda: np.exp(np.float64(1000.0))),\n",
    "    (\"10.0 ** 400\", lambda: 10.0**400, lambda: np.float64(10.0)**400),\n",
    "    (\"1e308 * 10\", lambda: 1e308 * 10, lambda: np.float64(1e308) * 10),\n",
    "    (\"math.inf - math.inf\", lambda: math.inf - math.inf, lambda: np.float64(np.inf) - np.inf),\n",
    "]\n",
    "print(f\"{'wyrażenie':22} {'Python':20} NumPy\")\n",
    "with np.errstate(all=\"ignore\"):\n",
    "    for opis, f, g in PRZYPADKI:\n",
    "        print(f\"{opis:22} {sprobuj(f):20} {sprobuj(g)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5851bbb4",
   "metadata": {},
   "source": [
    "On division by zero and on domain errors, Python raises an exception instead of returning $\\infty$\n",
    "or NaN — a deliberate design decision, but an inconsistent one: overflow in multiplication gives\n",
    "`inf`, overflow in `math.exp` and in exponentiation gives `OverflowError`, and\n",
    "`math.inf - math.inf` gives `nan` without any exception. NumPy sticks to the standard’s default\n",
    "behavior: it returns special values and reports raised flags only with a `RuntimeWarning`, which\n",
    "we silenced in the cell with `np.errstate(all=\"ignore\")`.\n",
    "\n",
    "### NaN in lists\n",
    "\n",
    "A value that is not equal to itself breaks the assumptions of many algorithms. Let us see how\n",
    "Python’s containers, the `max` function, sorting, and the median behave with NaN:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c81a667c",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = float(\"nan\")\n",
    "print(\"x == x:\", x == x, \"  [x] == [x]:\", [x] == [x], \"  x in [x]:\", x in [x],\n",
    "      \"  float('nan') in [float('nan')]:\", float(\"nan\") in [float(\"nan\")])\n",
    "print(\"słownik z dwoma kluczami NaN:\", {float(\"nan\"): 1, float(\"nan\"): 2})\n",
    "print(\"max([nan, 1, 2]) =\", max([x, 1.0, 2.0]), \"  max([1, nan, 2]) =\", max([1.0, x, 2.0]))\n",
    "for dane in ([3.0, x, 1.0, 2.0], [x, 3.0, 1.0, 2.0], [3.0, 1.0, x, 2.0]):\n",
    "    print(f\"sorted({dane}) = {sorted(dane)}   mediana: {statistics.median(dane)}\")\n",
    "print(\"NumPy:\", np.sort([3.0, x, 1.0, 2.0]), \"  np.median:\", np.median([3.0, x, 1.0, 2.0]),\n",
    "      \"  np.nanmedian:\", np.nanmedian([3.0, x, 1.0, 2.0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2b83966",
   "metadata": {},
   "source": [
    "Python’s containers compare object identity first and only then values (the language reference,\n",
    "§6.10.1). That is why the same NaN object “is equal” to itself inside a list, even though `x == x`\n",
    "is false. Two different NaN objects are neither the same object nor equal, so a dictionary treats\n",
    "them as two keys. The `max` function starts with the first element and replaces it only with\n",
    "a larger element; a comparison with NaN always gives false, so a NaN at the beginning of the list\n",
    "“wins,” while a NaN further down the list is skipped. Sorting assumes a total order, and every\n",
    "comparison with NaN gives false — so the result depends on where the NaN was. As a consequence,\n",
    "`statistics.median` of the same four numbers gives `nan`, $1.5$, or $2.5$. NumPy behaves\n",
    "consistently: NaN goes to the end, the median of data containing NaN is NaN, and the `np.nan…`\n",
    "functions skip missing values.\n",
    "\n",
    "### Signed zero in printed output\n",
    "\n",
    "Negative zero is equal to the ordinary zero, but it is printed with a minus sign — and this can be\n",
    "visible to the user:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "08e55293",
   "metadata": {},
   "outputs": [],
   "source": [
    "pomiary = [-0.04, 0.03, -0.2]\n",
    "print([f\"{t:.1f} °C\" for t in pomiary])\n",
    "print(\"round(-0.04, 1) =\", round(-0.04, 1), \"  max(0.0, -0.0) =\", max(0.0, -0.0),\n",
    "      \"  max(-0.0, 0.0) =\", max(-0.0, 0.0))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbc12429",
   "metadata": {},
   "source": [
    "A weather station will display “−0.0 °C”: rounding $-0.04$ to one decimal place gives $-0.0$.\n",
    "When its arguments are equal, the `max` function returns the first of them, so the result depends\n",
    "on the order, even though `0.0 == -0.0`.\n",
    "\n",
    "### The shortest decimal representation\n",
    "\n",
    "How should a `float` be printed in decimal? Its exact value has dozens of digits (for very large\n",
    "and very small numbers, even hundreds), and a representation that is too short does not allow the\n",
    "number to be recovered. Python follows the rule: print the shortest decimal representation that\n",
    "reads back as the same number. Let us check this property on $50{,}000$ random strings of $64$\n",
    "bits:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82f327be",
   "metadata": {},
   "outputs": [],
   "source": [
    "skonczone = powroty = najwiecej_cyfr = 0\n",
    "for _ in range(50_000):\n",
    "    x = z_bitow(random.getrandbits(64))       # losowe 64 bity — także liczby subnormalne\n",
    "    if math.isfinite(x):\n",
    "        skonczone += 1\n",
    "        r = repr(x)\n",
    "        powroty += float(r) == x\n",
    "        cyfry = r.split(\"e\")[0].lstrip(\"-\").replace(\".\", \"\").strip(\"0\")\n",
    "        najwiecej_cyfr = max(najwiecej_cyfr, len(cyfry))\n",
    "print(f\"zapisów repr, które wracają do tej samej liczby: {powroty} / {skonczone}\")\n",
    "print(\"najwięcej cyfr znaczących w repr:\", najwiecej_cyfr)\n",
    "print(repr(0.1), \"|\", f\"{0.1:.17g}\", \"|\", f\"{0.1:.25f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ce66f2e",
   "metadata": {},
   "source": [
    "All finite numbers came back unchanged; the remaining $20$ of the $50{,}000$ strings are infinities\n",
    "and NaNs (exponent $e=2047$, about $1/2048$ of all strings). Since Python 3.1, `repr` prints the\n",
    "shortest decimal string that reads back as the same number (David Gay’s algorithm). For binary64,\n",
    "no more than 17 significant digits are ever needed. That is why `0.1` looks innocent, even though\n",
    "the exact value of this number has 55 digits after the decimal point.\n",
    "\n",
    "## 6. Elementary functions: the standard only recommends\n",
    "\n",
    "The correct-rounding rule covers only the operations $+,-,\\cdot,/$, $\\sqrt{\\ }$, FMA, and\n",
    "conversions (Part 1, §1). For $\\sin$, $\\exp$, $\\log$, the standard (since 2008) merely\n",
    "**recommends** correct rounding; libraries usually promise an error below one or a few ulps.\n",
    "\n",
    "### An exact argument, a hard result: $\\sin(10^{22})$\n",
    "\n",
    "$10^{22}$ is a machine number (Part 1), so $\\sin(10^{22})$ is well defined. To compute it,\n",
    "however, one needs $10^{22}\\bmod 2\\pi$ — and for that, $\\pi$ to many digits:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7712b50",
   "metadata": {},
   "outputs": [],
   "source": [
    "mpmath.mp.dps = 60\n",
    "x = mpmath.mpf(10)**22\n",
    "print(\"math.sin(1e22) =\", math.sin(1e22), \"  dokładnie:\", mpmath.nstr(mpmath.sin(x), 20))\n",
    "for cyfry in (20, 30, 38):\n",
    "    pi_c = mpmath.mpf(mpmath.nstr(mpmath.pi, cyfry))          # π z tyloma cyframi znaczącymi\n",
    "    reszta = x - mpmath.nint(x / (2 * pi_c)) * 2 * pi_c\n",
    "    print(f\"redukcja z π o {cyfry} cyfrach:  sin =\", float(mpmath.sin(reszta)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb50197b",
   "metadata": {},
   "source": [
    "With $\\pi$ to 20 digits the result is wrong already in the first digit; almost 40 digits are\n",
    "needed. This follows from a simple computation: $10^{22}/(2\\pi)\\approx1.6\\cdot10^{21}$, so in the\n",
    "reduction the error of the approximation of $\\pi$ is multiplied by a number of order $10^{21}$,\n",
    "and for the remainder to still have $16$ correct digits, $\\pi$ must have about $21+16$ of them.\n",
    "The system library does this correctly. The FSIN instruction of the x87 coprocessor reduced the\n",
    "argument using an approximation of $\\pi$ with only 66 bits, so near multiples of $\\pi$ (already\n",
    "for $x\\approx\\pi$) its error was many orders of magnitude larger than Intel’s documentation\n",
    "promised (B. Dawson, 2014).\n",
    "\n",
    "### A good function, a bad argument\n",
    "\n",
    "The opposite situation: the library computes correctly, but the argument already carries an\n",
    "error. Near $10^{15}$ the gap between machine numbers is $0.125$, so the number $10^{15}+0.3$\n",
    "cannot be represented exactly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c805373",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 1e15 + 0.3\n",
    "print(\"1e15 + 0.3 zapisane jako\", repr(x), \"  (ulp(1e15) =\", math.ulp(1e15), \")\")\n",
    "print(\"math.sin(x)               =\", math.sin(x))\n",
    "prawdziwy = mpmath.sin(mpmath.mpf(10)**15 + mpmath.mpf(3) / 10)\n",
    "print(\"sin(10^15 + 0,3) dokładnie =\", mpmath.nstr(prawdziwy, 16))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97666dfb",
   "metadata": {},
   "source": [
    "The function correctly computed the sine of the number it received, namely $10^{15}+0.25$ (the\n",
    "printed `1000000000000000.2` is the shortest representation of this number, §5). The error arose\n",
    "earlier, when the argument was stored. The same mechanism spoiled the `float64` computations in\n",
    "§4 of the {doc}`worked example for Richardson’s theorem <../richardson/r2_przyklad>`.\n",
    "\n",
    "### How often does the library round incorrectly?\n",
    "\n",
    "We compare functions from the `math` module with correctly rounded values (mpmath, 200 bits):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b316533c",
   "metadata": {},
   "outputs": [],
   "source": [
    "mpmath.mp.prec = 200\n",
    "\n",
    "def dokladna(v):\n",
    "    \"\"\"Wartość mpmath zamieniona dokładnie na Fraction.\"\"\"\n",
    "    znak = -1 if v < 0 else 1\n",
    "    m, e = abs(v).man_exp\n",
    "    return znak * Fraction(m) * Fraction(2)**e\n",
    "\n",
    "FUNKCJE = [(\"exp\", math.exp, mpmath.exp, (-700, 700)),\n",
    "           (\"log\", math.log, mpmath.log, (1e-3, 1e3)),\n",
    "           (\"sin\", math.sin, mpmath.sin, (-100, 100)),\n",
    "           (\"tan\", math.tan, mpmath.tan, (-100, 100)),\n",
    "           (\"cbrt\", math.cbrt, mpmath.cbrt, (1e-3, 1e10)),\n",
    "           (\"gamma\", math.gamma, mpmath.gamma, (0.1, 170))]\n",
    "N = 2000\n",
    "print(f\"{'funkcja':8} {'niepoprawnie zaokrąglonych':>27} {'największy błąd':>16}\")\n",
    "for nazwa, f, g, (a, b) in FUNKCJE:\n",
    "    zle, najwiekszy = 0, 0.0\n",
    "    for _ in range(N):\n",
    "        x = random.uniform(a, b)\n",
    "        q, w = dokladna(g(mpmath.mpf(x))), f(x)\n",
    "        zle += w != float(q)\n",
    "        najwiekszy = max(najwiekszy, float(abs(Fraction(w) - q) / Fraction(math.ulp(w))))\n",
    "    print(f\"{nazwa:8} {zle:>20} / {N}  {najwiekszy:>12.3f} ulp\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b171b81",
   "metadata": {},
   "source": [
    "For the basic operations in Part 1 there was not a single mismatch. Here the number of\n",
    "incorrectly rounded results depends on the function: from isolated cases (`exp`, `log`) to more\n",
    "than half of the samples (`gamma`), and the largest error reaches almost $5$ ulps. The numbers\n",
    "come from the library of the system on which this page was built; on another computer they may\n",
    "differ. Correct rounding of transcendental functions is hard: it is not known in advance how many\n",
    "digits must be computed to decide the rounding (the “Table Maker’s Dilemma”). The CORE-MATH\n",
    "project provides such correctly rounded implementations.\n",
    "\n",
    "## 7. Tricks: formulas robust to rounding\n",
    "\n",
    "Many mathematically correct formulas lose accuracy in machine arithmetic or leave the range of\n",
    "representable numbers. What usually helps is to transform the formula or to use a library function\n",
    "that avoids the dangerous operation. We show four examples; in the last one, Muller’s sequence, no\n",
    "finite precision helps.\n",
    "\n",
    "### $(1+1/n)^n$\n",
    "\n",
    "The sequence $(1+1/n)^n$ tends to $e$. Let us compute it for $n$ from $10$ to $10^{17}$ directly\n",
    "and with a second, mathematically equivalent formula, and compare the errors of the two methods in\n",
    "a plot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8882fed4",
   "metadata": {},
   "outputs": [],
   "source": [
    "ks = np.arange(1, 17.01, 0.25)\n",
    "naiwnie, z_log1p = [], []\n",
    "for k in ks:\n",
    "    n = 10.0**k\n",
    "    naiwnie.append(abs((1 + 1 / n)**n - math.e))\n",
    "    z_log1p.append(abs(math.exp(n * math.log1p(1 / n)) - math.e))\n",
    "fig, ax = plt.subplots(figsize=(7, 3.2))\n",
    "ax.loglog(10**ks, naiwnie, \"o-\", ms=3, label=r\"$(1+1/n)^n$\")\n",
    "ax.loglog(10**ks, np.where(np.array(z_log1p) > 0, z_log1p, np.nan), \"s-\", ms=3,\n",
    "          label=r\"$\\exp(n\\cdot\\mathrm{log1p}(1/n))$\")\n",
    "ax.set_xlabel(\"$n$\")\n",
    "ax.set_ylabel(\"$|$wynik $- e|$\")\n",
    "ax.legend()\n",
    "ax.grid(alpha=0.3)\n",
    "plt.show()\n",
    "for k in (8, 12, 15, 16):\n",
    "    n = 10.0**k\n",
    "    print(f\"n = 1e{k}:  (1 + 1/n)**n = {(1 + 1 / n)**n!r:20}  exp(n·log1p(1/n)) = \"\n",
    "          f\"{math.exp(n * math.log1p(1 / n))!r}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4cca305c",
   "metadata": {},
   "source": [
    "Mathematically, $(1+1/n)^n\\to e$. Numerically, everything agrees up to $n\\approx10^{8}$; after\n",
    "that the error grows, and for $n=10^{16}$ the result is exactly $1$: $1+10^{-16}$ rounds to $1$.\n",
    "The reason: $\\fl(1+1/n)=(1+1/n)(1+\\delta)$ with $|\\delta|\\le u$, and\n",
    "$\\bigl((1+1/n)(1+\\delta)\\bigr)^n\\approx e\\cdot e^{n\\delta}$ — raising to the power $n$ multiplies\n",
    "the relative error by roughly $n$. For $n=10^8$ the bound gives $10^8u\\approx1.1\\cdot10^{-8}$,\n",
    "and the actual rounding error here is about $6\\cdot10^{-9}$. The error of the approximation itself\n",
    "contributes almost as much: $(1+1/n)^n\\approx e\\bigl(1-\\tfrac1{2n}\\bigr)$, that is,\n",
    "$5\\cdot10^{-9}$ in relative terms. Together this gives a relative error of about\n",
    "$1.1\\cdot10^{-8}$, visible in the printout. The remedy is the formula\n",
    "$(1+1/n)^n=\\exp\\bigl(n\\log(1+1/n)\\bigr)$, in which `math.log1p(x)` computes $\\log(1+x)$ with\n",
    "a relative error of order $u$ even for very small $x$, because it does not form $1+x$. Its twin,\n",
    "`math.expm1(x)`, computes $e^x-1$ just as accurately. In the plot, the curve for the formula with\n",
    "`log1p` decreases like $e/(2n)$: this is the error of the approximation $(1+1/n)^n\\approx e$\n",
    "itself, since rounding contributes only a relative error of order $10^{-16}$ here. The value\n",
    "$3.035$ for $n=10^{15}$ is the example from Part 1, §5: $\\fl(1+10^{-15})=1+1.11\\cdot10^{-15}$, so\n",
    "the direct formula in fact computes $e^{1.1102\\ldots}\\approx3.035$.\n",
    "\n",
    "### `hypot`\n",
    "\n",
    "The length of a vector, $\\sqrt{x^2+y^2}$, computed directly can leave the range of representable\n",
    "numbers even though the result itself lies well within it: for $x=10^{200}$ the square $10^{400}$ exceeds the\n",
    "range and gives $\\infty$, and for $x=10^{-200}$ the square vanishes in underflow. The function\n",
    "`math.hypot` avoids this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67e4dc64",
   "metadata": {},
   "outputs": [],
   "source": [
    "for x in (1e200, 1e-200):\n",
    "    wprost = math.sqrt(x * x + x * x)\n",
    "    print(f\"x = {x}:  sqrt(x*x + x*x) = {wprost!r:22}  hypot(x, x) = {math.hypot(x, x)!r}\")\n",
    "print(\"hypot(inf, nan) =\", math.hypot(math.inf, math.nan),\n",
    "      \"  sqrt(inf**2 + nan**2) =\", math.sqrt(math.inf**2 + math.nan**2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28c3044a",
   "metadata": {},
   "source": [
    "`hypot` scales its arguments, so there is neither overflow nor underflow in the intermediate\n",
    "computations. And one more subtlety: the standard (since 2008, §9.2.1) specifies the result\n",
    "$\\mathrm{hypot}(\\pm\\infty,\\mathrm{NaN})=+\\infty$ — whatever the other coordinate may be, the\n",
    "length of the vector is infinite. NaN does not always propagate.\n",
    "\n",
    "### Numerical derivative: the best $h\\approx\\sqrt\\varepsilon$\n",
    "\n",
    "The difference quotient $\\bigl(f(x+h)-f(x)\\bigr)/h$ approximates $f'(x)$ more and more accurately\n",
    "as $h$ decreases — but only in exact arithmetic. Let us examine the error for $f=\\sin$ at the point\n",
    "$x=1$ and for $h$ from $10^{-1}$ to $10^{-16}$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e10a8261",
   "metadata": {},
   "outputs": [],
   "source": [
    "hs = 10.0**-np.arange(1, 16.01, 0.25)\n",
    "bledy = [abs((math.sin(1 + h) - math.sin(1)) / h - math.cos(1)) for h in hs]\n",
    "fig, ax = plt.subplots(figsize=(7, 3.2))\n",
    "ax.loglog(hs, bledy, \"o-\", ms=3)\n",
    "ax.axvline(math.sqrt(2**-52), color=\"crimson\", ls=\"--\", lw=1, label=r\"$h=\\sqrt{\\varepsilon}$\")\n",
    "ax.set_xlabel(\"$h$\")\n",
    "ax.set_ylabel(\"błąd ilorazu różnicowego\")\n",
    "ax.legend()\n",
    "ax.grid(alpha=0.3)\n",
    "plt.show()\n",
    "i = int(np.argmin(bledy))\n",
    "print(f\"najmniejszy błąd {bledy[i]:.1e} dla h = {hs[i]:.1e};\"\n",
    "      f\"  sqrt(eps) = {math.sqrt(2**-52):.1e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9055bb31",
   "metadata": {},
   "source": [
    "The quotient $\\bigl(\\sin(1+h)-\\sin1\\bigr)/h$ has two errors. The truncation error, about\n",
    "$\\tfrac h2|\\sin''(1)|$, decreases with $h$. The rounding error: the numerator carries an error of\n",
    "order $\\varepsilon$, and division by $h$ amplifies it, so this error grows like $\\varepsilon/h$.\n",
    "The two are of the same order when $h$ is of order $\\sqrt\\varepsilon\\approx1.5\\cdot10^{-8}$ — and\n",
    "that is where, up to a small factor, the minimum in the plot lies. A smaller $h$ only does harm:\n",
    "for $h=10^{-16}$ we have $\\fl(1+h)=1$, the quotient is zero, and the error equals\n",
    "$\\cos1\\approx0.54$.\n",
    "\n",
    "### Muller’s sequence: rounding picks a different limit\n",
    "\n",
    "Muller’s sequence is a classic test of arithmetic: the recurrence is simple, and the computation\n",
    "in `float` gives a stable but wrong result.\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 side by side in `float` and exactly, with `Fraction` numbers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a30338b",
   "metadata": {},
   "outputs": [],
   "source": [
    "u, v = 2.0, -4.0\n",
    "U, V = Fraction(2), Fraction(-4)\n",
    "print(f\"{'n':>3} {'float':>22} {'dokładnie':>22}\")\n",
    "for n in range(2, 31):\n",
    "    u, v = v, 111 - 1130 / v + 3000 / (u * v)\n",
    "    U, V = V, 111 - 1130 / V + 3000 / (U * V)\n",
    "    if n in (2, 5, 10, 15, 16, 20, 25, 30):\n",
    "        print(f\"{n:3} {v!r:>22} {float(V)!r:>22}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bbf1e8e2",
   "metadata": {},
   "source": [
    "In exact arithmetic the sequence tends to $6$; in `float`, to $100$. The substitution\n",
    "$u_n=y_{n+1}/y_n$ gives the linear recurrence $y_{n+1}=111y_n-1130y_{n-1}+3000y_{n-2}$ with\n",
    "characteristic roots $5$, $6$, and $100$, so\n",
    "\n",
    "$$\n",
    "u_n=\\frac{\\alpha\\,100^{n+1}+\\beta\\,6^{n+1}+\\gamma\\,5^{n+1}}{\\alpha\\,100^{n}+\\beta\\,6^{n}+\\gamma\\,5^{n}} .\n",
    "$$\n",
    "\n",
    "The initial values give exactly $\\alpha=0$ (and $\\beta=-3$, $\\gamma=4$), hence the limit $6$. The\n",
    "first rounding turns $\\alpha$ into a tiny nonzero number, and $100^n$ eventually wins. No finite\n",
    "precision helps here — only exact computation or a proof that $\\alpha=0$.\n",
    "\n",
    "## 8. History: from a processor bug to formal proof\n",
    "\n",
    "```{admonition} Pentium FDIV (1994)\n",
    ":class: note\n",
    "Thomas Nicely of Lynchburg College was computing Brun’s constant — the sum of the reciprocals of\n",
    "the twin primes — and noticed that the Pentium processor divided some numbers incorrectly. The\n",
    "lookup table of the SRT division algorithm was missing 5 of its 1066 entries. In January 1995\n",
    "Intel took a charge of 475 million dollars. The industry responded with **formal proofs**:\n",
    "J S. Moore, T. Lynch, and M. Kaufmann proved in the ACL2 system that the division microcode of\n",
    "the AMD K5 processor returns the correctly rounded quotient, and J. Harrison at Intel verified\n",
    "floating-point algorithms in the HOL Light system. It is the same path — computation,\n",
    "verification, proof — as in Lecture 1.\n",
    "```\n",
    "\n",
    "## 9. Questions and exercises\n",
    "\n",
    "1. Why is the constant in Veltkamp’s splitting equal to $2^{27}+1$? How many significant bits do\n",
    "   the parts $a_h$ (`hi`) and $a_l$ (`a - hi`) have, and why?\n",
    "2. For which $a$ is the value $\\mathrm{fma}\\bigl(a,a,-\\fl(a\\cdot a)\\bigr)$ negative? What does its\n",
    "   sign depend on?\n",
    "3. Explain why `statistics.median` gives three different results for the same list containing\n",
    "   NaN. How can you guard against this?\n",
    "4. Find the smallest $n=2^k$ and the smallest $n=10^k$ for which `(1 + 1/n)**n` gives exactly\n",
    "   $1$.\n",
    "5. Why does $\\mathrm{hypot}(\\infty,\\mathrm{NaN})=\\infty$ make sense, while\n",
    "   $\\infty+\\mathrm{NaN}=\\infty$ would not?\n",
    "\n",
    "Computer exercises for this part — FastTwoSum, a counterexample for Neumaier summation, Muller’s\n",
    "sequence in mpmath, and the fast inverse square root in binary64 — are in the problem set\n",
    "{doc}`Lab 3 <../laboratoria/lab03_ieee754>` (Parts C and D, and exercise Z2 for independent\n",
    "practice).\n",
    "\n",
    "**References.** O. Møller, *Quasi double-precision in floating point addition*, BIT 5 (1965),\n",
    "37–50 · T. J. Dekker, *A floating-point technique for extending the available precision*,\n",
    "Numerische Mathematik 18 (1971), 224–242 · W. Kahan, *Further remarks on reducing truncation\n",
    "errors*, Communications of the ACM 8 (1965), 40 · A. Neumaier, *Rundungsfehleranalyse einiger\n",
    "Verfahren zur Summation endlicher Summen*, ZAMM 54 (1974), 39–51 · J. R. Shewchuk, *Adaptive\n",
    "precision floating-point arithmetic and fast robust geometric predicates*, Discrete &\n",
    "Computational Geometry 18 (1997), 305–363 · C. Lomont, *Fast inverse square root*, technical\n",
    "report, 2003 · D. Monniaux, *The pitfalls of verifying floating-point computations*, ACM\n",
    "TOPLAS 30 (2008), no. 3 · J.-M. Muller et al., *Handbook of Floating-Point Arithmetic*, 2nd ed.,\n",
    "Birkhäuser 2018 · [Clang: the `-ffp-contract` option](https://clang.llvm.org/docs/UsersManual.html) ·\n",
    "[Python: Floating Point Arithmetic: Issues and Limitations](https://docs.python.org/3/tutorial/floatingpoint.html) ·\n",
    "[Python: Value comparisons (§6.10.1)](https://docs.python.org/3/reference/expressions.html#value-comparisons) ·\n",
    "B. Dawson, [*Intel Underestimates Error Bounds by 1.3 quintillion*](https://randomascii.wordpress.com/2014/10/09/intel-underestimates-error-bounds-by-1-3-quintillion/), 2014 ·\n",
    "[The CORE-MATH project](https://core-math.gitlabpages.inria.fr/) ·\n",
    "J. L. Lions et al., [*Ariane 5 Flight 501 Failure — Report by the Inquiry Board*](https://www.esa.int/Newsroom/Press_Releases/Ariane_501_-_Presentation_of_Inquiry_Board_report), ESA 1996 ·\n",
    "T. Coe, T. Mathisen, C. Moler, V. Pratt, *Computational aspects of the Pentium affair*, IEEE\n",
    "Computational Science & Engineering 2 (1995), 18–30 · J S. Moore, T. Lynch, M. Kaufmann,\n",
    "*A mechanically checked proof of the AMD5K86 floating-point division program*, IEEE Transactions\n",
    "on Computers 47 (1998), 913–926 · J. Harrison, *Formal verification of floating point\n",
    "trigonometric functions*, FMCAD 2000, LNCS 1954, 217–233."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
