{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c000",
   "metadata": {},
   "source": [
    "# Lab 3: Floating-point arithmetic — IEEE 754 in practice\n",
    "\n",
    "**Duration:** 90 min · **Materials:** {doc}`IEEE 754: floating-point numbers from the inside <../ieee754/ieee754>` (deep dive) and {doc}`Lecture 1, §1.4 <../wyklady/w01_4_obliczenie_sprawdzenie_dowod>`\n",
    "\n",
    "## Learning goals\n",
    "\n",
    "After this session you will be able to:\n",
    "\n",
    "1. check the result of an operation on `float` numbers with exact arithmetic (`fractions.Fraction`);\n",
    "2. round rational numbers according to the IEEE 754 rule (round to nearest, ties to even) and explain what ties to even is for;\n",
    "3. show what subnormal numbers (gradual underflow) are good for;\n",
    "4. compute the exact error of an addition (FastTwoSum) and find inputs on which compensated summation fails;\n",
    "5. recognize computations for which no fixed precision is enough (Muller’s sequence).\n",
    "\n",
    "The exercises come from the chapter on IEEE 754 — it contains the explanations and the examples we build on.\n",
    "\n",
    "```{admonition} How to work with this set\n",
    ":class: tip\n",
    "Download the notebook (the download button at the top of the page → `.ipynb`), open it in VS Code, and fill in the cells marked `# TWÓJ KOD` (“your code”). Legend: ★ — basic exercise, ★★ — intermediate, ★★★ — optional challenge. The set ends with **exercises for independent practice**. The environment from Lab 1 is enough: apart from the standard library, you only need the `mpmath` package, which is installed together with SymPy.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c001",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math, random, struct\n",
    "from fractions import Fraction\n",
    "from decimal import Decimal, localcontext, ROUND_HALF_UP, ROUND_HALF_EVEN\n",
    "import mpmath\n",
    "\n",
    "random.seed(2026)\n",
    "\n",
    "def bity(x):\n",
    "    \"\"\"64 bity liczby x (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))\n",
    "\n",
    "print(\"bity(1.0) =\", hex(bity(1.0)), \"  następna liczba po 1.0:\", z_bitow(bity(1.0) + 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c002",
   "metadata": {},
   "source": [
    "## Part A — rounding (≈ 30 min)\n",
    "\n",
    "### A1. Drift under round half up ★\n",
    "\n",
    "Mathematically, $(u+v)-v=u$. In the chapter ({doc}`Part 1, §3 <../ieee754/i1_standard>`), the sequence $u\\leftarrow(u+v)-v$ computed with three digits for $u=1.00$, $v=0.555$ drifted under round half up: $1.00\\to1.01\\to1.02\\to\\dots$, while with ties to even it stayed put. The function `ciag` computes the successive terms with the `decimal` module."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c003",
   "metadata": {},
   "outputs": [],
   "source": [
    "def ciag(u, v, cyfry, regula, kroki=8):\n",
    "    \"\"\"Wyrazy u, (u+v)-v, ... w arytmetyce dziesiętnej o podanej liczbie cyfr i regule zaokrąglania.\"\"\"\n",
    "    with localcontext() as ctx:\n",
    "        ctx.prec, ctx.rounding = cyfry, regula\n",
    "        u, v = Decimal(u), Decimal(v)\n",
    "        wynik = [+u]\n",
    "        for _ in range(kroki):\n",
    "            u = (u + v) - v\n",
    "            wynik.append(u)\n",
    "    return wynik\n",
    "\n",
    "print(\"połówki w górę:\", \" \".join(map(str, ciag(\"1.00\", \"0.555\", 3, ROUND_HALF_UP))))\n",
    "print(\"do parzystej:  \", \" \".join(map(str, ciag(\"1.00\", \"0.555\", 3, ROUND_HALF_EVEN))))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c004",
   "metadata": {},
   "source": [
    "**Exercise.** (a) Find other $u$, $v$ and a number of digits for which the sequence drifts under round half up (all 9 terms are distinct) but stays put with ties to even. Start with two digits.\n",
    "(b) For two digits, go through all pairs $u=1.0,\\ 1.1,\\ \\dots,\\ 9.9$ and $v=0.01,\\ 0.02,\\ \\dots,\\ 0.99$. How many pairs drift under round half up? What do their values of $v$ have in common? Is there a pair for which, with ties to even, the sequence changes more than once?\n",
    "*(Hint: `Decimal(i).scaleb(-1)` is the number $i/10$ written with one digit after the decimal point.)*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c005",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c006",
   "metadata": {},
   "source": [
    "*Your answer (A1(b)):* …"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c007",
   "metadata": {},
   "source": [
    "### A2. Does `float(Fraction)` round correctly? ★★\n",
    "\n",
    "The conversion `float(q)` for `q` of type `Fraction` should return $q$ rounded to 53 significand bits: to the nearest machine number and, in case of a tie, to the one with the even significand. Let us check this with an independent computation.\n",
    "\n",
    "**Exercise.** (a) Write a function `zaokraglij(q, p)` that returns the positive rational number `q` (a `Fraction`) rounded to `p` significand bits (round to nearest, ties to even) — also as a `Fraction`. *Hint:* find $e$ such that $2^e\\le q<2^{e+1}$ (`numerator.bit_length()` and `denominator.bit_length()` will help), multiply $q$ by $2^{p-1-e}$, round to an integer (`divmod(·, 1)` returns the integer part and the remainder), and divide back.\n",
    "(b) Check on 10,000 random fractions (numerator and denominator up to $2^{200}$) that `Fraction(float(q)) == zaokraglij(q, 53)`.\n",
    "(c) What do $2^{53}+1$, $2^{53}+3$, $1+2^{-53}$, and $1+3\\cdot2^{-53}$ round to? Explain each case.\n",
    "\n",
    "This exercise will come in handy in exercise Z1 at the end of the set. A reference version of the function `zaokraglij` is in {doc}`Part 2, §4 <../ieee754/i2_implementacja>` of the chapter — look there only after you have written your own version."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c008",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c009",
   "metadata": {},
   "source": [
    "*Your answer (A2(c)):* …"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c010",
   "metadata": {},
   "source": [
    "## Part B — gradual underflow (≈ 10 min)\n",
    "\n",
    "### B1. $x\\ne y\\Rightarrow x-y\\ne0$ ★\n",
    "\n",
    "The smallest positive normal binary64 number is $2^{-1022}$; below it lie the subnormal numbers. Thanks to them, $x\\ne y\\iff x-y\\ne0$ holds for finite $x,y$ ({doc}`Part 1, §4 <../ieee754/i1_standard>`). In *flush to zero* (FTZ) mode, a result smaller than $2^{-1022}$ is replaced by zero — the function `bez_subnormalnych` simulates this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c011",
   "metadata": {},
   "outputs": [],
   "source": [
    "def bez_subnormalnych(v):\n",
    "    \"\"\"Tryb „flush to zero”: wynik mniejszy od najmniejszej liczby normalnej staje się zerem.\"\"\"\n",
    "    return 0.0 if abs(v) < 2.0**-1022 else v"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c012",
   "metadata": {},
   "source": [
    "**Exercise.** Draw 100,000 random pairs $x,y$ from the interval $[0,2^{-1020}]$ (`random.uniform`).\n",
    "(a) Count the pairs with $x\\ne y$ for which nevertheless `x - y == 0`.\n",
    "(b) Count the pairs with $x\\ne y$ for which `bez_subnormalnych(x - y) == 0`. What fraction of all pairs is this? Justify the result with a probability computation *(hint: $2^{-1020}=4\\cdot2^{-1022}$)*."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c013",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c014",
   "metadata": {},
   "source": [
    "*Your answer (B1(b)):* …"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c015",
   "metadata": {},
   "source": [
    "## Part C — the exact error of addition (≈ 30 min)\n",
    "\n",
    "### C1. FastTwoSum ★\n",
    "\n",
    "Dekker (1971): if $|a|\\ge|b|$, then with rounding to nearest (and barring overflow), for $s=\\fl(a+b)$ and $e=\\fl\\bigl(b-\\fl(s-a)\\bigr)$ we have $a+b=s+e$ **exactly** — the error of the addition is itself a machine number. The chapter ({doc}`Part 2, §2 <../ieee754/i2_implementacja>`) presents the TwoSum algorithm of Møller and Knuth, which does not need the condition $|a|\\ge|b|$ but performs six operations instead of three."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c016",
   "metadata": {},
   "outputs": [],
   "source": [
    "def fast_two_sum(a, b):\n",
    "    s = a + b\n",
    "    e = b - (s - a)\n",
    "    return s, e"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c017",
   "metadata": {},
   "source": [
    "**Exercise.** (a) Check on 100,000 random pairs (generated with the function `losowa`) that for $|a|\\ge|b|$ the decomposition is exact: `Fraction(a) + Fraction(b) == Fraction(s) + Fraction(e)`.\n",
    "(b) How often is the decomposition inexact when the arguments are given in the reverse order?\n",
    "(c) Give an example with integers in which `fast_two_sum` gets it wrong for $|a|<|b|$, and explain step by step what happens."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c018",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c019",
   "metadata": {},
   "source": [
    "*Your answer (C1(c)):* …"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c020",
   "metadata": {},
   "source": [
    "### C2. A counterexample for Neumaier summation ★★\n",
    "\n",
    "Neumaier summation ({doc}`Part 2, §2 <../ieee754/i2_implementacja>`) collects the parts lost in the additions in the correction `c`. Since Python 3.12, the built-in function `sum` works the same way. It usually gives the correctly rounded result — but, unlike `math.fsum`, not always."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c021",
   "metadata": {},
   "outputs": [],
   "source": [
    "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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c022",
   "metadata": {},
   "source": [
    "**Exercise.** Find a short list (three or four numbers; for two numbers `neumaier` always gives the correctly rounded result) that `neumaier` sums differently from `math.fsum`. Use `Fraction` to check which result is the correctly rounded sum. What does the built-in `sum` return for this list? *(Hint: a tie. What happens when the correction `c` itself has to be rounded?)*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c023",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c024",
   "metadata": {},
   "source": [
    "*Your answer (C2):* …"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c025",
   "metadata": {},
   "source": [
    "## Part D — Muller’s sequence (≈ 15 min)\n",
    "\n",
    "### D1. How many digits are enough? ★★\n",
    "\n",
    "The sequence $u_0=2$, $u_1=-4$, $u_{n+1}=111-\\dfrac{1130}{u_n}+\\dfrac{3000}{u_nu_{n-1}}$ tends to $6$, but computed in `float` it tends to $100$ ({doc}`Part 2, §7 <../ieee754/i2_implementacja>`).\n",
    "\n",
    "**Exercise.** (a) Compute $u_n$ for $n\\le100$ in `float`, exactly (`Fraction`), and in mpmath with 50 and with 100 digits (`with mpmath.workdps(50): ...`).\n",
    "(b) For each precision, find the first $n$ for which $|u_n-u_n^{\\text{exact}}|>1$.\n",
    "(c) By how much does this point shift when we add 50 digits? Explain it with the formula from the chapter: the deviation from $6$ grows like $(100/6)^n$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c026",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c027",
   "metadata": {},
   "source": [
    "*Your answer (D1(c)):* …"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c028",
   "metadata": {},
   "source": [
    "## Exercises for independent practice\n",
    "\n",
    "The rules are the same as in Lab 1: the exercises are for your own practice, and each of them is **a single function** with the given name that **returns** its result. The standard library (`fractions`, `math`, `struct`) is enough.\n",
    "\n",
    "### Z1. Four rounding modes ★★\n",
    "\n",
    "Write a function `zaokraglij(q, p, tryb=\"najblizsza\")` that returns the rational number `q` (a `Fraction` of any sign, including $0$) rounded to `p` significand bits ($p\\ge2$) — as a `Fraction`. The modes are the four rounding modes of the IEEE 754 standard:\n",
    "\n",
    "- `\"najblizsza\"` — round to nearest, ties to even significand (the default mode),\n",
    "- `\"do_zera\"` — toward zero (truncation),\n",
    "- `\"w_gore\"` — toward $+\\infty$,\n",
    "- `\"w_dol\"` — toward $-\\infty$.\n",
    "\n",
    "The exponent is unbounded (there is no overflow and there are no subnormal numbers).\n",
    "\n",
    "Examples: `zaokraglij(Fraction(1, 3), 2) == Fraction(3, 8)`, `zaokraglij(Fraction(-1, 3), 2, \"w_gore\") == Fraction(-1, 4)`, `zaokraglij(Fraction(7, 4), 2) == 2`.\n",
    "\n",
    "*Hint:* exercise A2. For $p=53$ you can check the result yourself: `float(q)` is the result of mode `\"najblizsza\"`, and the results of the other modes are `float(q)` or an adjacent machine number (`math.nextafter`). Such a check makes sense only for $q$ whose absolute value lies in the range of normal binary64 numbers.\n",
    "\n",
    "### Z2. Fast inverse square root in binary64 ★\n",
    "\n",
    "Write a function `odwrotny_pierwiastek64(x, kroki)` that, for a positive `float` $x$, returns an approximation of $1/\\sqrt x$ computed with the trick from {doc}`Part 2, §1 <../ieee754/i2_implementacja>`, carried over to binary64:\n",
    "\n",
    "1. the initial approximation $y$ is the `float` whose 64 bits are `0x5FE6EB50C7B537A9 - (bity(x) >> 1)` (the binary64 constant given by M. Robertson in 2012);\n",
    "2. then the Newton step `y = y * (1.5 - 0.5 * x * y * y)` is applied `kroki` times.\n",
    "\n",
    "Paste the functions `bity` and `z_bitow` from the beginning of the set into your solution.\n",
    "\n",
    "Examples: `odwrotny_pierwiastek64(2.0, 0) == 0.7162250423950712`, `odwrotny_pierwiastek64(2.0, 1) == 0.706929650795464` (the exact value is $1/\\sqrt2=0.7071067811865475\\ldots$).\n",
    "\n",
    "Check on your own computer how the largest relative error on the interval $[1,4)$ decreases after 0, 1, 2, and 3 steps. Why is it enough to examine this interval?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c029",
   "metadata": {},
   "outputs": [],
   "source": [
    "def zaokraglij(q, p, tryb=\"najblizsza\"):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "def odwrotny_pierwiastek64(x, kroki):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "# Testy lokalne — odkomentuj, gdy funkcje będą gotowe:\n",
    "# assert zaokraglij(Fraction(1, 3), 2) == Fraction(3, 8)\n",
    "# assert zaokraglij(Fraction(-1, 3), 2, \"w_gore\") == Fraction(-1, 4)\n",
    "# assert zaokraglij(Fraction(7, 4), 2) == 2\n",
    "# assert odwrotny_pierwiastek64(2.0, 0) == 0.7162250423950712\n",
    "# assert odwrotny_pierwiastek64(2.0, 1) == 0.706929650795464\n",
    "# print(\"Testy przykładowe przechodzą.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
