{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d212a496",
   "metadata": {},
   "source": [
    "# Python for mathematicians: first steps\n",
    "\n",
    "This section is not a programming course — we assume the basics of programming (at WMI UAM, from\n",
    "the course *Programowanie*). Here we collect the elements of Python that a mathematician uses most\n",
    "often, and those in which it is easiest to make mistakes. For each of them we ask the same question:\n",
    "**which mathematical object does a given type or language construct correspond to, and where does\n",
    "this correspondence end?** Python’s integers are genuine integers, but a `float` is not a real\n",
    "number, and a list comprehension, although it resembles set-builder notation, describes a finite\n",
    "computation.\n",
    "\n",
    "The style of work we will practice is *computational thinking*.\n",
    "It consists of three steps:\n",
    "\n",
    "1. **abstraction** — we state the problem precisely: what is given, what is the output, and what\n",
    "   conditions the output must satisfy;\n",
    "2. **automation** — we write the solution as a program;\n",
    "3. **analysis** — we run the program, check it on cases we know, and assess what the result is:\n",
    "   a proof, an approximation, or merely a conjecture.\n",
    "\n",
    "## Python as a calculator: integers\n",
    "\n",
    "Integers (`int`) in Python have **unlimited precision**. The interpreter stores them as sequences\n",
    "of digits in a large base (in CPython it is $2^{30}$) and lengthens this representation\n",
    "as needed. Computations are therefore exact regardless of the size of the numbers, and the only\n",
    "limits are memory and time. The time grows with the length of the representation: adding two $n$-digit numbers takes\n",
    "about $n$ digit operations, and schoolbook multiplication about $n^2$ (for very large numbers, CPython\n",
    "switches to the faster Karatsuba algorithm). The `int` type thus implements the set $\\Z$ literally.\n",
    "\n",
    "One practical caveat: in current versions of Python, converting a number to a decimal string\n",
    "(`str`, `print`) is limited by default to $4300$ digits, so, e.g., `str(math.factorial(2000))`\n",
    "raises a `ValueError`; the limit can be changed with the function `sys.set_int_max_str_digits`, and\n",
    "the computations themselves are not affected by it. To begin, let us compute $2^{100}$; the result has $31$ digits,\n",
    "and Python prints it in full:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "202a0ca0",
   "metadata": {},
   "outputs": [],
   "source": [
    "2**100"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "07163743",
   "metadata": {},
   "source": [
    "The factorial $100! = 1 \\cdot 2 \\cdots 100$ has more than a hundred and fifty digits, and yet Python computes it\n",
    "instantly and without any rounding. Let us count its digits and compute their sum:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "677766bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "n = math.factorial(100)\n",
    "len(str(n)), sum(int(c) for c in str(n))      # liczba cyfr i suma cyfr 100!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e54ed2a0",
   "metadata": {},
   "source": [
    "The number $100!$ has $158$ digits, and the sum of its digits is $648$. The second result is easy to check\n",
    "partially without a computer: $9$ divides $100!$, and every natural number is congruent modulo $9$ to the sum\n",
    "of its digits, so the digit sum must be divisible by $9$. Indeed, $648 = 9 \\cdot 72$. Such\n",
    "an independent check of a result is a good habit.\n",
    "\n",
    "Python has three operators related to division. The operator `/` approximates the real\n",
    "quotient: for arguments of type `int`, its result is always of type `float`, even when the division can be carried out\n",
    "in the integers. The operators `//` and `%` implement **division with remainder** in $\\Z$: the first gives the quotient,\n",
    "the second the remainder."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de60c555",
   "metadata": {},
   "outputs": [],
   "source": [
    "17 / 5, 17 // 5, 17 % 5        # dzielenie zmiennopozycyjne, iloraz całkowity, reszta"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92aa9d25",
   "metadata": {},
   "source": [
    "More precisely: for integers $a$ and $b \\neq 0$, Python defines\n",
    "\n",
    "$$\n",
    "a \\mathbin{//} b = \\left\\lfloor \\frac{a}{b} \\right\\rfloor, \\qquad\n",
    "a \\bmod b = a - b \\left\\lfloor \\frac{a}{b} \\right\\rfloor ,\n",
    "$$\n",
    "\n",
    "where $a \\bmod b$ is the result of the `%` operator. Hence **always** $a = (a \\mathbin{//} b)\\cdot b + (a \\bmod b)$,\n",
    "and for $b > 0$ the remainder lies in $\\{0, 1, \\dots, b-1\\}$ — also for negative $a$. It is thus\n",
    "exactly the remainder from the theorem on division with remainder. (For $b < 0$ the remainder has the sign of the divisor:\n",
    "$b < a \\bmod b \\le 0$.) This convention, called floor division, agrees with the theorem on division\n",
    "with remainder for positive divisors,\n",
    "but differs from the languages C and Java, in which the integer quotient is rounded toward zero:\n",
    "there, $-7$ divided by $2$ gives the quotient $-3$ and the remainder $-1$. Let us check what Python returns\n",
    "(the function `divmod` gives the quotient and the remainder at once):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f04ae50",
   "metadata": {},
   "outputs": [],
   "source": [
    "a, b = -7, 2\n",
    "a // b, a % b, (a // b) * b + a % b == a, divmod(a, b)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46fc206c",
   "metadata": {},
   "source": [
    "We have $-7 = (-4) \\cdot 2 + 1$: the quotient is $\\lfloor -3.5 \\rfloor = -4$, and the remainder $1$ lies in\n",
    "$\\{0, 1\\}$, as the theorem on division with remainder requires.\n",
    "\n",
    "```{warning}\n",
    "In Python, exponentiation is written `**`. The symbol `^` denotes **bitwise exclusive or**\n",
    "(XOR): `2^10` gives `8`, because $0010_2 \\oplus 1010_2 = 1000_2$. In SageMath, the preparser turns `^`\n",
    "into exponentiation, so the same string has a different meaning there.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6765e1ef",
   "metadata": {},
   "outputs": [],
   "source": [
    "2**10, 2^10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57a323e7",
   "metadata": {},
   "source": [
    "The `math` module contains exact number-theoretic and combinatorial functions that work on\n",
    "integers of any size:\n",
    "\n",
    "* `math.gcd(a, b)` and `math.lcm(a, b)` — the greatest common divisor and the least common\n",
    "  multiple;\n",
    "* `math.isqrt(n)` — the integer square root $\\lfloor \\sqrt{n} \\rfloor$, computed exactly\n",
    "  (unlike `int(math.sqrt(n))`, which goes through `float` and may give a wrong result\n",
    "  for large $n$);\n",
    "* `math.comb(n, k)` — the binomial coefficient $\\binom{n}{k} = \\frac{n!}{k!\\,(n-k)!}$;\n",
    "* `math.factorial(n)` and `math.prod(ciąg)` — the factorial and the product of the elements of a sequence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21a82ed9",
   "metadata": {},
   "outputs": [],
   "source": [
    "math.gcd(1071, 462), math.isqrt(10**20 + 1), math.comb(52, 5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbe00c94",
   "metadata": {},
   "source": [
    "Let us read off the results. The equality $\\gcd(1071, 462) = 21$ is a classic example of the Euclidean\n",
    "algorithm at work; we will return to the algorithm below. Next, $\\lfloor \\sqrt{10^{20}+1} \\rfloor = 10^{10}$, because\n",
    "$(10^{10})^2 \\le 10^{20}+1 < (10^{10}+1)^2$. (Here `int(math.sqrt(n))` would give the same result; the difference\n",
    "shows up, e.g., for $n = 10^{16} - 1$: this number rounds to the `float` equal to $10^{16}$, so\n",
    "`int(math.sqrt(n))` returns $10^8$, although $\\lfloor\\sqrt{n}\\rfloor = 10^8 - 1$.) Finally, $\\binom{52}{5} = 2{,}598{,}960$ is the number\n",
    "of five-element subsets of a deck of $52$ cards, that is, of all possible poker hands."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9845f3aa",
   "metadata": {},
   "source": [
    "## Floating-point numbers — a first warning\n",
    "\n",
    "The `float` type is a 64-bit IEEE 754 floating-point number (the same as `double`\n",
    "in C). Every finite number of this type has the form $\\pm m \\cdot 2^{e}$, where $m$ is an\n",
    "integer, $0 \\le m < 2^{53}$, and the exponent satisfies $-1074 \\le e \\le 971$. This gives a precision of about\n",
    "$16$ decimal digits. It follows from this form that every finite `float` is a fraction\n",
    "whose denominator is a power of two. On the other hand, a rational number $p/q$ written in lowest\n",
    "terms has a finite binary expansion if and only if $q$ is a power of two.\n",
    "The fractions $\\tfrac{1}{10}$, $\\tfrac{2}{10}$, and $\\tfrac{3}{10}$ do not satisfy this condition, so `float`\n",
    "**does not represent them exactly** — it stores the machine numbers nearest to them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ffa734ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "0.1 + 0.2, 0.1 + 0.2 == 0.3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a395181d",
   "metadata": {},
   "source": [
    "Each of the fractions $0.1$, $0.2$, and $0.3$ has been replaced by the nearest machine number, and the result\n",
    "of the addition has been rounded once more. The sum lands on the machine number **adjacent** to the one\n",
    "we write as `0.3` — hence the final digit `4`, and the comparison is false. We take this example\n",
    "apart bit by bit in the deep dive {doc}`../ieee754/i2_implementacja`.\n",
    "\n",
    "The built-in function `round` performs rounding as well. When a number lies **exactly** halfway between two\n",
    "possible values, Python chooses the one whose last digit is even (*round half to even*). The IEEE 754\n",
    "standard uses the same rule: unlike the schoolbook rule of rounding “halves up,”\n",
    "it does not systematically shift the sum of many rounded values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61023eb7",
   "metadata": {},
   "outputs": [],
   "source": [
    "round(2.5), round(3.5), round(0.125, 2)    # zaokrąglanie „do parzystej” (banker's rounding)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5dece706",
   "metadata": {},
   "source": [
    "So `round(2.5)` gives $2$, and `round(3.5)` gives $4$. The result of `round(0.125, 2)`, namely $0.12$,\n",
    "is also rounding to even: $0.125 = 2^{-3}$ is a machine number, so the tie is\n",
    "genuine. When a number cannot be stored exactly, there is no tie at all, and the result depends on\n",
    "which side of the halfway point the stored value lies. For example, `round(2.675, 2)` gives $2.67$,\n",
    "because the literal `2.675` is stored as a number about $1.8\\cdot 10^{-16}$ smaller than $2.675$.\n",
    "\n",
    "When we need exact computation with fractions, we use the type `fractions.Fraction`. It stores\n",
    "a rational number as a pair of integers — a numerator and a positive denominator — in lowest\n",
    "terms, so operations on it are exact operations in the field $\\Q$. The price is time:\n",
    "numerators and denominators can grow quickly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de3a2272",
   "metadata": {},
   "outputs": [],
   "source": [
    "from fractions import Fraction\n",
    "Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c802969c",
   "metadata": {},
   "source": [
    "The `Fraction` constructor also accepts a number of type `float` and returns its **exact** value.\n",
    "This way we can see what the computer really stores when we write `0.1`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d83ce3e4",
   "metadata": {},
   "outputs": [],
   "source": [
    "Fraction(0.1)          # dokładna wartość liczby zmiennopozycyjnej „0.1”"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b44bb28",
   "metadata": {},
   "source": [
    "The denominator $36{,}028{,}797{,}018{,}963{,}968$ is $2^{55}$, in line with what we said\n",
    "about binary expansions. The stored number is slightly larger than $\\tfrac{1}{10}$: the difference\n",
    "is exactly $\\tfrac{1}{5 \\cdot 2^{55}} \\approx 5.55 \\cdot 10^{-18}$.\n",
    "\n",
    "We will study floating-point arithmetic in detail later in the course (it is one of the course’s main\n",
    "topics; see also the deep dive {doc}`../ieee754/ieee754`). For now, remember: **comparing\n",
    "`float` values with the `==` operator is usually a mistake**. Instead, we use exact computation or the function\n",
    "`math.isclose(a, b)`, which checks the condition\n",
    "\n",
    "$$\n",
    "|a - b| \\le \\max\\bigl(r \\cdot \\max(|a|, |b|),\\ t\\bigr)\n",
    "$$\n",
    "\n",
    "with a relative tolerance $r$ (the argument `rel_tol`, by default $10^{-9}$) and an absolute tolerance $t$ (the argument\n",
    "`abs_tol`, by default $0$). When comparing with zero, the relative condition is of no use, so an absolute\n",
    "tolerance must be given.\n",
    "\n",
    "## Data types and their mathematical counterparts\n",
    "\n",
    "Every built-in type has a natural mathematical counterpart, but the correspondence is not always\n",
    "exact. The `int` type implements $\\Z$ (within the limits of memory). The finite values of type\n",
    "`float`, on the other hand, form a **finite** subset of $\\Q$ — fractions whose denominators are powers of two,\n",
    "with bounded numerators and denominators (precisely: the numbers $\\pm m \\cdot 2^{e}$ described above) —\n",
    "extended by $\\pm\\infty$ and the value NaN (*not a number*). The table gives the full overview;\n",
    "in it, the collections (from `str` down) correspond to finite objects:\n",
    "\n",
    "| Python | Example | Mathematics |\n",
    "|---|---|---|\n",
    "| `int` | `-3`, `2**100` | $\\Z$ (exactly) |\n",
    "| `float` | `0.1`, `1e-9` | approximations of real numbers |\n",
    "| `complex` | `1 + 2j` | approximations of complex numbers |\n",
    "| `bool` | `True`, `False` | truth values (`True == 1`) |\n",
    "| `str` | `\"abc\"` | words over an alphabet |\n",
    "| `list` | `[1, 2, 2]` | finite sequences |\n",
    "| `tuple` | `(1, 2)` | tuples (pairs, triples, …) |\n",
    "| `set` | `{1, 2}` | finite sets |\n",
    "| `dict` | `{1: 'a', 2: 'b'}` | functions with a finite domain |\n",
    "\n",
    "The function `type` gives the type of a value. Let us check the types of the results of a few operations; the last expression\n",
    "shows how Python treats truth values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "337c1f33",
   "metadata": {},
   "outputs": [],
   "source": [
    "type(7), type(7 / 1), type(1j**2), True + True"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae0eba46",
   "metadata": {},
   "source": [
    "The division `7 / 1` gives a `float`, although the result is an integer: the type of the result depends on the operator, not\n",
    "on the value. The power `1j**2` is the complex number $-1$, of type `complex`. Finally, `True + True`\n",
    "equals $2$, because the type `bool` is a subtype of `int`, and `True` and `False` are simply $1$ and $0$."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aba054e3",
   "metadata": {},
   "source": [
    "## List comprehensions as set-builder notation\n",
    "\n",
    "The mathematical notation $\\{\\, n^2 : n \\in \\{1,\\dots,10\\},\\ 2 \\nmid n \\,\\}$ has an almost\n",
    "literal counterpart in Python — a **list comprehension** or a **set comprehension**.\n",
    "Note the range:\n",
    "`range(1, 11)` is the set $\\{1, 2, \\dots, 10\\}$, because the range `range(a, b)` contains $a$ but does not\n",
    "contain $b$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "86de6416",
   "metadata": {},
   "outputs": [],
   "source": [
    "[n**2 for n in range(1, 11) if n % 2 == 1]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "561d840d",
   "metadata": {},
   "source": [
    "Several `for` loops in one expression correspond to several bound variables, and the `if` condition\n",
    "to the conditions imposed on these variables. The set comprehension below is\n",
    "\n",
    "$$\n",
    "\\{(a, b, c) : 1 \\le a < b < c < 30,\\ a^2 + b^2 = c^2,\\ \\gcd(a, b) = 1\\},\n",
    "$$\n",
    "\n",
    "that is, the set of **primitive Pythagorean triples** with hypotenuse less than $30$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b628e8f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "{(a, b, c) for c in range(1, 30) for b in range(1, c) for a in range(1, b)\n",
    " if a*a + b*b == c*c and math.gcd(a, b) == 1}           # pierwotne trójki pitagorejskie"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "951ee1b6",
   "metadata": {},
   "source": [
    "The search is exhaustive, so these are all such triples. This agrees with a classical\n",
    "theorem: the primitive triples are exactly the triples $(m^2 - n^2,\\ 2mn,\\ m^2 + n^2)$, up to\n",
    "the order of the legs, for coprime $m > n \\ge 1$ of opposite parity.\n",
    "Five such pairs satisfy the condition $m^2 + n^2 < 30$: $(2, 1)$, $(3, 2)$, $(4, 1)$, $(4, 3)$, and $(5, 2)$.\n",
    "\n",
    "Quantifiers and summation-like operators also have counterparts: `all` ($\\forall$), `any`\n",
    "($\\exists$), `sum` ($\\Sigma$), `math.prod` ($\\Pi$), `max`, `min`. They work on **finite**\n",
    "sequences and follow the usual conventions for the empty set: `all([])` is `True`, `any([])` is\n",
    "`False`, the empty sum is $0$, and the empty product is $1$. The exceptions are `max` and `min`: for an empty sequence\n",
    "they raise a `ValueError`, because the empty set has no largest or smallest element.\n",
    "Let us check Gauss’s formula\n",
    "$1 + 2 + \\dots + n = \\frac{n(n+1)}{2}$ for all $n < 1000$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec56e3ba",
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 1000\n",
    "all(sum(range(1, n + 1)) == n * (n + 1) // 2 for n in range(N))     # ∀ n < N: 1+…+n = n(n+1)/2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "539387db",
   "metadata": {},
   "source": [
    "The result `True` is a **verification of finitely many cases** (a thousand of them: $n = 0, 1, \\dots, 999$), not a proof of a theorem\n",
    "about all $n \\in \\N$. (Note also that the division `// 2` is exact here, because the product $n(n+1)$\n",
    "is always even.) We will return to the difference between verification and proof in the section\n",
    "{doc}`w01_4_obliczenie_sprawdzenie_dowod`, where we will prove the same formula formally.\n",
    "\n",
    "## Functions, loops, conditionals\n",
    "\n",
    "The Euclidean algorithm rests on two equalities: $\\gcd(a, b) = \\gcd(b,\\ a \\bmod b)$ for\n",
    "$b \\neq 0$, and $\\gcd(a, 0) = |a|$. The remainders decrease in absolute value, so the algorithm\n",
    "always terminates. Let us write it with a step counter (we will use it again in the\n",
    "lab):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54470c91",
   "metadata": {},
   "outputs": [],
   "source": [
    "def nwd(a, b):\n",
    "    \"\"\"Zwraca (NWD(a, b), liczba kroków dzielenia z resztą).\"\"\"\n",
    "    kroki = 0\n",
    "    while b != 0:\n",
    "        a, b = b, a % b\n",
    "        kroki += 1\n",
    "    return abs(a), kroki\n",
    "\n",
    "nwd(1071, 462), nwd(89, 55)       # 89 i 55 to kolejne liczby Fibonacciego"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09e0e97f",
   "metadata": {},
   "source": [
    "For the pair $(1071, 462)$ three steps suffice, while for the consecutive Fibonacci numbers $89$ and $55$\n",
    "it takes as many as nine. This is no accident: by Lamé’s theorem (1844), consecutive Fibonacci numbers are\n",
    "the worst case for the Euclidean algorithm, and for $a \\ge b > 0$ the number of steps never exceeds\n",
    "five times the number of decimal digits of the smaller number (see exercise B4 in the problem set\n",
    "{doc}`../laboratoria/lab01_srodowisko_python`). The assumption $a \\ge b$ matters: for $a < b$ our\n",
    "function performs an extra step that merely swaps the arguments, and, e.g., `nwd(8, 13)`\n",
    "needs $6$ steps, although $5 \\cdot 1 = 5$.\n",
    "\n",
    "**The Collatz problem.** Let $T(n) = n/2$ for even $n$ and $T(n) = 3n + 1$ otherwise.\n",
    "The Collatz conjecture (1937) states that for every $n \\ge 1$ the sequence $n, T(n), T(T(n)), \\dots$ eventually\n",
    "reaches $1$. It has been verified by computer for an enormous range of numbers, but nobody knows a proof.\n",
    "Even so, the process itself is easy to program:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a72dba23",
   "metadata": {},
   "outputs": [],
   "source": [
    "def collatz(n):\n",
    "    ciag = [n]\n",
    "    while n != 1:\n",
    "        n = n // 2 if n % 2 == 0 else 3 * n + 1\n",
    "        ciag.append(n)\n",
    "    return ciag\n",
    "\n",
    "c = collatz(27)\n",
    "len(c) - 1, max(c)          # liczba kroków i największa wartość dla n = 27"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5863b3a4",
   "metadata": {},
   "source": [
    "For $n = 27$ it takes $111$ steps, and along the way the sequence climbs as high as $9232$. Such irregular\n",
    "behavior, already for a small starting number, shows well why the conjecture is hard.\n",
    "\n",
    "**Recursion and memoization.** The Fibonacci numbers satisfy $F_0 = 0$, $F_1 = 1$, and\n",
    "$F_n = F_{n-1} + F_{n-2}$ for $n \\ge 2$. The definition transcribed directly as a recursive function is correct,\n",
    "but useless for large $n$: computing $F_n$ requires $2F_{n+1} - 1$ function calls (an easy\n",
    "proof by induction), and $F_n \\approx \\varphi^n / \\sqrt{5}$, where $\\varphi = \\frac{1+\\sqrt{5}}{2}$,\n",
    "grows exponentially. The decorator `functools.lru_cache` remembers the values already computed, so\n",
    "each of the numbers $F_0, F_1, \\dots, F_n$ is computed only once:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "47630867",
   "metadata": {},
   "outputs": [],
   "source": [
    "from functools import lru_cache\n",
    "\n",
    "@lru_cache(maxsize=None)\n",
    "def fib(n):\n",
    "    return n if n < 2 else fib(n - 1) + fib(n - 2)\n",
    "\n",
    "fib(100)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87e248dd",
   "metadata": {},
   "source": [
    "With memoization, the result appears instantly. Without `@lru_cache`, the same definition would make\n",
    "$2F_{101} - 1 > 10^{21}$ calls, that is, in practice it would never finish — a good\n",
    "illustration that a *correct* program need not be a *useful* one.\n",
    "\n",
    "## Modules we will use\n",
    "\n",
    "Python’s standard library and a few external packages cover almost everything we\n",
    "need in this course:\n",
    "\n",
    "| Module | What for |\n",
    "|---|---|\n",
    "| `math`, `fractions`, `decimal` | mathematical functions, exact fractions, decimal arithmetic |\n",
    "| `itertools` | combinatorics: `product`, `combinations`, `permutations` |\n",
    "| `random` | pseudorandom numbers (reproducible once the seed is fixed: `random.seed(0)`) |\n",
    "| `numpy` | fast computations on arrays of numbers (vectors, matrices) |\n",
    "| `matplotlib` | plots |\n",
    "| `sympy` | symbolic computation |\n",
    "| `mpmath` | arbitrary-precision arithmetic and interval arithmetic |\n",
    "\n",
    "Finally, let us plot Collatz trajectories for several starting values. On the vertical axis we use\n",
    "a logarithmic scale, because the values vary over several orders of magnitude."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50c5e487",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(7, 3.2))\n",
    "for start in (27, 31, 41, 47):\n",
    "    ax.plot(collatz(start), lw=1.2, label=f\"n = {start}\")\n",
    "ax.set_yscale(\"log\")\n",
    "ax.set_xlabel(\"krok\")\n",
    "ax.set_ylabel(\"wartość\")\n",
    "ax.legend()\n",
    "ax.set_title(\"Trajektorie Collatza\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6498fd04",
   "metadata": {},
   "source": [
    "The curves look like shifted copies of a single trajectory — and that is exactly what they are. The sequence for $27$\n",
    "passes through the other three starting values\n",
    "($27 \\to 82 \\to 41 \\to 124 \\to 62 \\to 31 \\to 94 \\to 47 \\to \\dots$), so their trajectories are\n",
    "final segments of the trajectory of $27$ and reach the same maximum, $9232$.\n",
    "\n",
    "## Good habits\n",
    "\n",
    "* Write small functions with readable names and a short description (a *docstring*).\n",
    "* Test on cases you know, e.g., `assert nwd(12, 18)[0] == 6`.\n",
    "* Fix the seed of the random number generator (`random.seed(0)`) so that results are reproducible.\n",
    "* Separate the **computation** from the **conclusion**: the output of a program is a piece of data, not a theorem. Before\n",
    "  you interpret it, ask whether it checks finitely many cases, whether it is an approximation,\n",
    "  or whether it follows from a proof."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
