{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5af7a928",
   "metadata": {},
   "source": [
    "# Example: an expression whose sign cannot be seen\n",
    "\n",
    "Richardson's theorem says that **there is no algorithm** deciding whether an expression is\n",
    "negative somewhere. What does this look like in a concrete example? We take the machine from the proof\n",
    "({doc}`r2_dowod`, §2–§5) and feed it the equation\n",
    "\n",
    "$$\n",
    "x_1^3+x_2^3+x_3^3=a \\qquad (x_1,x_2,x_3\\in\\mathbb Z).\n",
    "$$\n",
    "\n",
    "For each number $a$ the machine produces an explicit expression $A_a(t)$ in one variable, built\n",
    "solely from integers, $\\pi$, $t$, the operations $+,-,\\cdot$ and the sine. We ask: **is\n",
    "$A_a(t)\\ge0$ for all $t$?** — for four values: $a=3,\\ 4,\\ 42,\\ 114$.\n",
    "\n",
    "Numerics gives the same answer in all four cases. The truth, however, varies:\n",
    "\n",
    "* $a=4$: yes, $A_4>0$ everywhere — the proof takes three lines of number theory;\n",
    "* $a=3$: no — but the place where $A_3<0$ lies around $t\\approx10^{13}$, and $t$ has to be\n",
    "  given to about a hundred digits;\n",
    "* $a=42$: no — this has been known only since 2019, and a suitable $t$ has about 2770 significant digits;\n",
    "* $a=114$: **nobody knows**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10acda35",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "# Ukryta w książce: wykresy także jako PDF (wektorowe) do wersji do druku.\n",
    "%config InlineBackend.figure_formats = ['png', 'pdf']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2109b9f7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "import signal\n",
    "import time\n",
    "from itertools import product\n",
    "import numpy as np\n",
    "import sympy as sp\n",
    "import mpmath as mp\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "905d6317",
   "metadata": {},
   "source": [
    "## 1. The expression $A_a(t)$\n",
    "\n",
    "We follow the proof exactly, with one change: the unknowns are **integers** (of either\n",
    "sign), not natural numbers.\n",
    "\n",
    "* **Equation:** $P_a(\\mathbf x)=x_1^3+x_2^3+x_3^3-a$, $n=3$ unknowns.\n",
    "* **Weights** (Definition 2.4): $k_i=M_{\\partial Q/\\partial x_i}$ for $Q=P_a^2$. Since\n",
    "  $\\partial Q/\\partial x_i=6x_i^2P_a$, Lemma 2.1 gives\n",
    "\n",
    "  $$\n",
    "  k_i(\\mathbf x)=38\\,(x_i^2+2)^2\\,M_a(\\mathbf x),\\qquad\n",
    "  M_a(\\mathbf x)=\\sum_{j=1}^3(x_j^2+2)^3+a^2+2 .\n",
    "  $$\n",
    "\n",
    "* **Penalty** (Definition 3.2): $f_a(\\mathbf x)=4^4\\bigl[P_a(\\mathbf x)^2+\\sum_{i=1}^3\\sin^2(\\pi x_i)\\,k_i(\\mathbf x)^4\\bigr]$.\n",
    "* **Curve** (Definition 4.3): $\\Gamma_3(t)=\\bigl(h(t),\\,h(g(t)),\\,g(g(t))\\bigr)$, where\n",
    "  $h(t)=t\\sin t$, $g(t)=t\\sin t^3$.\n",
    "* **Result** (Definition 5.2): $G_a(t)=f_a\\bigl(\\Gamma_3(t)\\bigr)$ and $A_a(t)=G_a(t)-1$.\n",
    "\n",
    "Written out: for $s=t\\sin t^3$ and $u_1=t\\sin t$, $u_2=s\\sin s$, $u_3=s\\sin s^3$,\n",
    "\n",
    "$$\n",
    "A_a(t)=256\\Bigl[\\bigl(u_1^3+u_2^3+u_3^3-a\\bigr)^2\n",
    "+\\sum_{i=1}^3\\sin^2(\\pi u_i)\\,\\bigl(38\\,(u_i^2+2)^2M\\bigr)^4\\Bigr]-1,\n",
    "$$\n",
    "\n",
    "where $M=\\sum_{j=1}^3(u_j^2+2)^3+a^2+2$.\n",
    "\n",
    "```{admonition} Proposition P.1 (Theorem 5.3 for integer unknowns)\n",
    ":class: important\n",
    "Let $a\\in\\mathbb Z$.\n",
    "1. If $a=m_1^3+m_2^3+m_3^3$ for some $m_i\\in\\mathbb Z$, then for every $\\varepsilon>0$\n",
    "   and $M\\ge0$ there is $t>M$ with $A_a(t)<-1+\\varepsilon$; in particular, $A_a(t)<0$ for some $t$.\n",
    "2. If there are no such $m_i$, then $A_a(t)>0$ for **every** $t\\in\\mathbb R$.\n",
    "```\n",
    "\n",
    "**Proof.** The proof of Theorem 3.4 carries over word for word: in Step 2 we round $x_i$ to\n",
    "the nearest integer (of either sign), and in Step 4 the number $P_a(\\mathbf m)$ is\n",
    "an integer because $P_a$ has integer coefficients. We get $f_a(\\mathbf x)>1$ for all\n",
    "$\\mathbf x\\in\\mathbb R^3$ when there are no solutions — so the squares from Corollary 3.7 are not needed.\n",
    "When $P_a(\\mathbf m)=0$, we have $f_a(\\mathbf m)=0$, and the density of the curve (Theorem 4.4) and the continuity\n",
    "of $f_a$ give points $t>M$ with $G_a(t)<\\varepsilon$ — as in the proof of Theorem 5.3. $\\blacksquare$\n",
    "\n",
    "Let us check that the weights really are the majorants from Lemma 2.1 (the same function `majoranta` as in §2\n",
    "of the proof):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54ec9e07",
   "metadata": {},
   "outputs": [],
   "source": [
    "def majoranta(e):\n",
    "    \"\"\"Majoranta lokalna M_e (Lemat 2.1), rekurencyjnie po drzewie wyrażenia.\"\"\"\n",
    "    if e.is_number or e.is_Symbol:\n",
    "        return e**2 + 2\n",
    "    if e.is_Add:\n",
    "        return sp.Add(*[majoranta(c) for c in e.args])\n",
    "    if e.is_Mul:\n",
    "        return sp.Mul(*[majoranta(c) for c in e.args])\n",
    "    if e.is_Pow and e.exp.is_Integer and e.exp > 0:\n",
    "        return majoranta(e.base) ** e.exp\n",
    "    if isinstance(e, sp.exp):\n",
    "        return sp.exp(majoranta(e.args[0]))\n",
    "    if isinstance(e, (sp.sin, sp.cos)):\n",
    "        return sp.Integer(2)\n",
    "    raise ValueError(f\"węzeł spoza języka: {e.func}\")\n",
    "\n",
    "x = sp.symbols('x1:4')\n",
    "for a in (3, 4, 42, 114):\n",
    "    P = sum(xi**3 for xi in x) - a\n",
    "    M = sum((xi**2 + 2)**3 for xi in x) + a**2 + 2\n",
    "    for xi in x:\n",
    "        assert sp.expand(majoranta(sp.diff(P**2, xi)) - 38 * (xi**2 + 2)**2 * M) == 0\n",
    "print(\"wagi k_i = 38 (x_i² + 2)² M_a zgadzają się z Lematem 2.1 (a = 3, 4, 42, 114)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "664a8d59",
   "metadata": {},
   "source": [
    "The weights agree with Lemma 2.1 identically (the comparison after expansion is symbolic,\n",
    "not numerical). Now let us build the whole expression $A_a(t)$ in SymPy and check that it indeed\n",
    "contains only integers, $\\pi$, $t$, arithmetic operations and the sine:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1715206a",
   "metadata": {},
   "outputs": [],
   "source": [
    "t = sp.Symbol('t', real=True)\n",
    "\n",
    "def A_symb(a):\n",
    "    \"\"\"A_a(t) = f_a(Γ_3(t)) - 1 jako wyrażenie SymPy.\"\"\"\n",
    "    s = t * sp.sin(t**3)                                    # s = g(t)\n",
    "    u = (t * sp.sin(t), s * sp.sin(s), s * sp.sin(s**3))    # Γ_3(t)\n",
    "    P = sum(ui**3 for ui in u) - a\n",
    "    M = sum((ui**2 + 2)**3 for ui in u) + a**2 + 2\n",
    "    k = [38 * (ui**2 + 2)**2 * M for ui in u]\n",
    "    kara = sum(sp.sin(sp.pi * ui)**2 * ki**4 for ui, ki in zip(u, k))\n",
    "    return 256 * (P**2 + kara) - 1\n",
    "\n",
    "A42 = A_symb(42)\n",
    "print(\"funkcje w A_42:\", {f.func for f in A42.atoms(sp.Function)})\n",
    "print(\"liczba operacji w drzewie A_42:\", sp.count_ops(A42))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "454c47d5",
   "metadata": {},
   "source": [
    "The only function in the tree is the sine, and the function `count_ops` counted $223$ operations in it —\n",
    "the expression is large, but completely explicit. For the computations we use the same formula written out directly — once for ordinary numbers\n",
    "(`ctx=mp`), once for intervals (`ctx=mp.iv`):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3222d071",
   "metadata": {},
   "outputs": [],
   "source": [
    "def G(t, a, ctx=mp):\n",
    "    \"\"\"G_a(t) = f_a(Γ_3(t)); ctx = mp (liczby) albo mp.iv (przedziały).\"\"\"\n",
    "    sin, pi = ctx.sin, ctx.pi\n",
    "    s = t * sin(t**3)\n",
    "    u = (t * sin(t), s * sin(s), s * sin(s**3))\n",
    "    P = u[0]**3 + u[1]**3 + u[2]**3 - a\n",
    "    M = sum((ui**2 + 2)**3 for ui in u) + a**2 + 2\n",
    "    k = [38 * (ui**2 + 2)**2 * M for ui in u]\n",
    "    return 256 * (P**2 + sum(sin(pi * ui)**2 * ki**4 for ui, ki in zip(u, k)))\n",
    "\n",
    "def A(t, a):\n",
    "    return G(t, a) - 1\n",
    "\n",
    "# zgodność z wyrażeniem SymPy w kilku punktach\n",
    "mp.mp.dps = 50\n",
    "F42 = sp.lambdify(t, A42, 'mpmath')\n",
    "for v in ('0.7', '2.5', '13.1'):\n",
    "    blad = abs(F42(mp.mpf(v)) / A(mp.mpf(v), 42) - 1)\n",
    "    print(f\"t = {v}: błąd względny {mp.nstr(blad, 3)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d4d6cf0",
   "metadata": {},
   "source": [
    "The two versions agree at the three test points with a relative error of order $10^{-50}$, i.e., at the\n",
    "limit of the precision we set ($50$ digits).\n",
    "\n",
    "## 2. Four equations\n",
    "\n",
    "| $a$ | solution in integers | known since |\n",
    "|---|---|---|\n",
    "| $3$ | $1^3+1^3+1^3$ (also $4^3+4^3+(-5)^3$) | always |\n",
    "| $4$ | **none** (residues modulo 9) | elementary |\n",
    "| $42$ | $(-80538738812075974)^3+80435758145817515^3+12602123297335631^3$ | A. Booker and A. Sutherland, 2019 |\n",
    "| $114$ | **unknown** | the smallest open case |\n",
    "\n",
    "The solution for $42$ was found after 1.3 million hours of computation on the Charity Engine distributed network;\n",
    "all numbers below $114$ (except those ruled out by their residue modulo 9) already have known\n",
    "representations, and $114$ is the smallest open case (as of September 2026; see the\n",
    "references at the end). Let us check what can be checked:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49a2a96b",
   "metadata": {},
   "outputs": [],
   "source": [
    "rozwiazania = {3: (1, 1, 1),\n",
    "               42: (-80538738812075974, 80435758145817515, 12602123297335631)}\n",
    "for a, m in rozwiazania.items():\n",
    "    print(f\"a = {a}: suma sześcianów {m} = {sum(v**3 for v in m)}\")\n",
    "reszty = {(p**3 + q**3 + r**3) % 9 for p, q, r in product(range(9), repeat=3)}\n",
    "print(\"reszty modulo 9 sum trzech sześcianów:\", sorted(reszty))\n",
    "print(\"a mod 9:\", {a: a % 9 for a in (3, 4, 42, 114)})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b40c02a",
   "metadata": {},
   "source": [
    "Cubes leave only the residues $0,\\pm1$ modulo 9, so a sum of three cubes cannot leave the residue\n",
    "$4$ or $5$. For $a=4$ there are no solutions; for $42$ and $114$ the residue modulo 9 rules nothing out.\n",
    "\n",
    "## 3. What numerics sees\n",
    "\n",
    "Let us plot $\\log_{10}G_a(t)$ on the interval $[0,6]$; the dashed line is the level $G_a=1$, i.e., $A_a=0$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3aeb7935",
   "metadata": {},
   "outputs": [],
   "source": [
    "mp.mp.dps = 40\n",
    "ts = [mp.mpf(i) / 400 for i in range(2401)]\n",
    "kolory = {3: '#059669', 4: '#64748b', 42: '#d97706', 114: '#4f46e5'}\n",
    "fig, ax = plt.subplots(figsize=(8, 3.4))\n",
    "for a in (3, 4, 42, 114):\n",
    "    ys = [float(mp.log10(G(v, a))) for v in ts]\n",
    "    ax.plot([float(v) for v in ts], ys, lw=0.7, color=kolory[a], label=f\"a = {a}\")\n",
    "ax.axhline(0, color='crimson', lw=1, ls='--')\n",
    "ax.set_xlabel('t')\n",
    "ax.set_ylabel(r'$\\log_{10} G_a(t)$')\n",
    "ax.set_title('Krajobraz: wszędzie wysoko nad poziomem G = 1', fontsize=10)\n",
    "ax.legend(fontsize=8, ncol=4)\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6a3d1317",
   "metadata": {},
   "source": [
    "On the whole interval $[0,6]$ all four graphs lie high above the level $G_a=1$; the lowest value,\n",
    "at $t=0$, is $G_3(0)=2304$, i.e., $\\log_{10}G_3\\approx3.4$. Let us also check a dense grid on\n",
    "$[0,20]$ and $3000$ random points from $[0,10^6]$, working with a precision of 90 digits so that $\\sin t^3$\n",
    "and $\\sin s^3$ are computed correctly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "498febaa",
   "metadata": {},
   "outputs": [],
   "source": [
    "random.seed(2026)\n",
    "mp.mp.dps = 90\n",
    "siatka = [mp.mpf(i) / 500 for i in range(10001)]                # [0, 20], krok 0,002\n",
    "losowe = [mp.mpf(random.uniform(0, 1e6)) for _ in range(3000)]  # z [0, 10^6]\n",
    "print(\"   a | najmniejsze G_a na siatce | w punktach losowych\")\n",
    "for a in (3, 4, 42, 114):\n",
    "    m1, m2 = min(G(v, a) for v in siatka), min(G(v, a) for v in losowe)\n",
    "    print(f\"{a:>4} | {mp.nstr(m1, 4):>25} | {mp.nstr(m2, 4):>19}\")\n",
    "tmin = min(losowe, key=lambda v: G(v, 3))\n",
    "r4 = G(tmin, 4) / G(tmin, 3) - 1\n",
    "r114 = G(tmin, 114) / G(tmin, 3) - 1\n",
    "print(\"w tym punkcie losowym:  G_4/G_3 − 1 =\", mp.nstr(r4, 3),\n",
    "      \"  G_114/G_3 − 1 =\", mp.nstr(r114, 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a27ff6bb",
   "metadata": {},
   "source": [
    "The smallest value on the grid is $G_a(0)=256a^2$: the curve passes through the lattice point\n",
    "$(0,0,0)$, but there $P_a=-a\\neq0$. At the random points the smallest values agree for all $a$\n",
    "to many digits — for large $t$ the constant $a$ is negligible compared with $u_i^3$.\n",
    "\n",
    "Numerics says the same thing for all four equations: $A_a$ is positive, and hugely so.\n",
    "If we guessed on this basis, we would conclude that none of the four equations has solutions —\n",
    "and we would be wrong at least twice (for $a=3$ and $a=42$).\n",
    "\n",
    "## 4. The floating-point trap\n",
    "\n",
    "The same formula in ordinary `float64` arithmetic:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68c20fb2",
   "metadata": {},
   "outputs": [],
   "source": [
    "def G64(t, a):\n",
    "    \"\"\"Ta sama formuła w arytmetyce float64 (NumPy).\"\"\"\n",
    "    with np.errstate(over='ignore', invalid='ignore'):\n",
    "        s = t * np.sin(t**3)\n",
    "        u = (t * np.sin(t), s * np.sin(s), s * np.sin(s**3))\n",
    "        P = sum(ui**3 for ui in u) - a\n",
    "        M = sum((ui**2 + 2)**3 for ui in u) + a**2 + 2\n",
    "        k = [38 * (ui**2 + 2)**2 * M for ui in u]\n",
    "        kara = sum(np.sin(np.pi * ui)**2 * ki**4 for ui, ki in zip(u, k))\n",
    "        return 256 * (P**2 + kara)\n",
    "\n",
    "mp.mp.dps = 120\n",
    "print(\"       t |     float64 | mpmath, 120 cyfr\")\n",
    "for v in (2.5, 50.0, 1e3, 1e5, 1e7):\n",
    "    print(f\"{v:>8g} | {G64(np.float64(v), 3):.4e} | {mp.nstr(G(mp.mpf(v), 3), 5)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a665632e",
   "metadata": {},
   "source": [
    "For small $t$ the results agree. For $t=10^5$ the number $t^3=10^{15}$ is still exact in `float64`\n",
    "($10^{15}<2^{53}\\approx9\\cdot10^{15}$), and $\\sin t^3$ comes out correct. However, $s=t\\sin t^3$ is no longer\n",
    "exact: its error, of order $10^{-12}$, produces an error of about $0.05$ in $s^3\\approx6\\cdot10^{14}$, and $\\sin s^3$\n",
    "depends on $s^3$ modulo $2\\pi$. Beyond that, `float64` computes the sines of “different” numbers than it should.\n",
    "\n",
    "## 5. A certificate for $a=3$\n",
    "\n",
    "Since $1^3+1^3+1^3=3$, Proposition P.1 guarantees negative values of $A_3$. Where? The proof is\n",
    "constructive: Theorem 4.4 for $n=3$ amounts to applying Lemma 4.2 twice — first $s$ with\n",
    "$\\Gamma_2(s)\\approx(1,1)$, then $w$ with $h(w)\\approx1$ and $g(w)=s$; then\n",
    "$\\Gamma_3(w)=\\bigl(h(w),\\Gamma_2(g(w))\\bigr)\\approx(1,1,1)$.\n",
    "\n",
    "How close do we have to get? At the point $(1,1,1)$ the weights are $k_i=31464$, so\n",
    "$G_3\\approx256\\sum_i\\pi^2\\varepsilon_i^2k_i^4$ for deviations $\\varepsilon_i$ — we need\n",
    "$|\\varepsilon_i|\\lesssim10^{-11}$. We take $\\delta=10^{-12}$; we will check the result rigorously at the end."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af8ea5ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "h = lambda t: t * mp.sin(t)\n",
    "g = lambda t: t * mp.sin(t**3)\n",
    "dh = lambda t: mp.sin(t) + t * mp.cos(t)\n",
    "dg = lambda t: mp.sin(t**3) + 3 * t**3 * mp.cos(t**3)\n",
    "\n",
    "def zero(F, dF, lo, hi, tol):\n",
    "    \"\"\"Miejsce zerowe F na [lo, hi], gdy F zmienia znak: Newton z bisekcją.\"\"\"\n",
    "    flo, t = F(lo), (lo + hi) / 2\n",
    "    while hi - lo > tol:\n",
    "        ft = F(t)\n",
    "        if (ft > 0) == (flo > 0):\n",
    "            lo, flo = t, ft\n",
    "        else:\n",
    "            hi = t\n",
    "        krok = ft / dF(t)\n",
    "        nowy = t - krok\n",
    "        if not (lo < nowy < hi) or abs(krok) > (hi - lo) / 2:\n",
    "            nowy = (lo + hi) / 2               # krok Newtona niepewny — bisekcja\n",
    "        elif abs(krok) < tol:\n",
    "            return nowy\n",
    "        t = nowy\n",
    "    return (lo + hi) / 2\n",
    "\n",
    "def podnies(a, b, delta, tol, M=0):\n",
    "    \"\"\"Lemat 4.2: w > M, |h(w) - a| < δ, |g(w) - b| ≤ tol (w dowodzie g(w) = b).\n",
    "    Przedziały poszukiwań są dokładnie takie jak w dowodzie lematu.\"\"\"\n",
    "    a, b, delta, pi = mp.mpf(a), mp.mpf(b), mp.mpf(delta), mp.pi\n",
    "    R = max(mp.mpf(M), abs(b), mp.mpf(1), 4 * pi / delta) * (1 + mp.mpf('1e-9'))\n",
    "    dolna = mp.sqrt(R**2 + delta / 2)\n",
    "    k = int(mp.ceil((max(dolna, abs(a)) - pi / 2) / (2 * pi))) + 1\n",
    "    tol_v = mp.mpf(10)**(-mp.mp.dps // 2)\n",
    "    v = zero(lambda t: h(t) - a, dh, 2*pi*k + pi/2, 2*pi*k + 3*pi/2, tol_v)\n",
    "    u = mp.sqrt(v**2 - delta / 2)\n",
    "    assert (v - u) * (v + 1) < delta / 2 and v**3 - u**3 > 2 * pi   # (4.1), (4.2)\n",
    "    nast = lambda c: c + 2 * pi * mp.ceil((u**3 - c) / (2 * pi))\n",
    "    tp, tm = mp.cbrt(nast(pi / 2)), mp.cbrt(nast(3 * pi / 2))\n",
    "    lo, hi = min(tp, tm), max(tp, tm)\n",
    "    w = zero(lambda t: g(t) - b, dg, lo, hi, tol / (3 * hi**3) / 10)\n",
    "    assert abs(h(w) - a) < delta and abs(g(w) - b) <= tol\n",
    "    return w\n",
    "\n",
    "def podnies3(cel, delta, tol):\n",
    "    \"\"\"Twierdzenie 4.4 dla n = 3; błąd |g(w) - s| mnoży się w g(s) przez ≈ 3s³.\"\"\"\n",
    "    c1, c2, c3 = map(mp.mpf, cel)\n",
    "    s = podnies(c2, c3, delta, tol)\n",
    "    return podnies(c1, s, delta, tol / (3 * abs(s)**3) / 10)\n",
    "\n",
    "M = sum((v**2 + 2)**3 for v in (1, 1, 1)) + 3**2 + 2\n",
    "print(\"wagi w punkcie (1, 1, 1):\", [38 * (v**2 + 2)**2 * M for v in (1, 1, 1)])\n",
    "mp.mp.dps = 260\n",
    "t0 = podnies3((1, 1, 1), mp.mpf('1e-12'), mp.mpf('1e-14'))\n",
    "print(\"t₀ ≈\", mp.nstr(t0, 30))\n",
    "odchylenia = [v - 1 for v in (h(t0), h(g(t0)), g(g(t0)))]\n",
    "print(\"Γ_3(t₀) − (1, 1, 1) =\", [mp.nstr(d, 3) for d in odchylenia])\n",
    "print(\"A_3(t₀) =\", mp.nstr(A(t0, 3), 12))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf911e8e",
   "metadata": {},
   "source": [
    "The deviations of the first two coordinates from $1$ are of order $10^{-13}$, the third is practically\n",
    "exact, and $A_3(t_0)\\approx-0.99992$. The number $A_3(t_0)$ computed in 260-digit arithmetic is not yet a proof. The proof is provided by\n",
    "**interval arithmetic**: every operation rounds outward, so the result is an interval that is\n",
    "guaranteed to contain the true value. We write $t_0$ as a string with 110 significant digits — this is\n",
    "our certificate:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78f1fa3c",
   "metadata": {},
   "outputs": [],
   "source": [
    "t0_napis = mp.nstr(t0, 110)\n",
    "print(\"t₀ =\", t0_napis)\n",
    "for dps in (220, 400):\n",
    "    mp.iv.dps = dps\n",
    "    I = G(mp.iv.mpf(t0_napis), 3, ctx=mp.iv)\n",
    "    print(f\"{dps} cyfr: G_3(t₀) ∈ {mp.iv.nstr(I, 10)};  A_3(t₀) < 0: {I.b < 1}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16921f14",
   "metadata": {},
   "source": [
    "At both precisions the interval is narrow and lies below $1$ ($G_3(t_0)\\approx7.87\\cdot10^{-5}$), so\n",
    "$A_3(t_0)<0$ is proved. A hundred digits is no exaggeration — here is what happens when we round $t_0$ more coarsely:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "284b3ead",
   "metadata": {},
   "outputs": [],
   "source": [
    "mp.iv.dps = 400\n",
    "for cyfry in (60, 80, 100, 110):\n",
    "    I = G(mp.iv.mpf(mp.nstr(t0, cyfry)), 3, ctx=mp.iv)\n",
    "    gora = mp.nstr(mp.mpf(I.b.b), 4)\n",
    "    print(f\"t₀ z {cyfry:>3} cyframi: G_3 ≤ {gora:>11};  A_3 < 0: {I.b < 1}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b73ac52",
   "metadata": {},
   "source": [
    "With $60$ and $80$ digits the rounded point already lies outside the interval on which $A_3<0$: there $G_3$ is\n",
    "of order $10^{497}$ and $10^{339}$, respectively (the resulting intervals are narrow, so $A_3>0$ at these points); from $100$ digits on,\n",
    "the upper endpoint drops below $1$, i.e., $A_3<0$ is proved. How wide is the interval around $t_0$\n",
    "on which $A_3<0$? And what will `float64` see?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35569a59",
   "metadata": {},
   "outputs": [],
   "source": [
    "def brzeg(kierunek):\n",
    "    \"\"\"Odległość od t₀ do miejsca, w którym A_3 wraca do zera.\"\"\"\n",
    "    krok = mp.mpf('1e-100')\n",
    "    while A(t0 + kierunek * krok, 3) < 0:          # oddalamy się, aż A_3 ≥ 0\n",
    "        krok *= 2\n",
    "    lo, hi = mp.mpf(0), krok\n",
    "    for _ in range(200):                           # potem bisekcja\n",
    "        mid = (lo + hi) / 2\n",
    "        lo, hi = (mid, hi) if A(t0 + kierunek * mid, 3) < 0 else (lo, mid)\n",
    "    return lo\n",
    "\n",
    "szer = brzeg(-1) + brzeg(+1)\n",
    "print(\"długość przedziału wokół t₀, na którym A_3 < 0:\", mp.nstr(szer, 3))\n",
    "print(\"liczba punktów siatki o takim kroku w [0, t₀]:\", mp.nstr(t0 / szer, 2))\n",
    "t64 = float(t0)\n",
    "print(\"float64 w t₀:\", G64(np.float64(t64), 3), \"  (t₀ jako float64:\", t64, \")\")\n",
    "print(\"prawdziwe G_3 w tym punkcie float64:\", mp.nstr(G(mp.mpf(t64), 3), 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45933f82",
   "metadata": {},
   "source": [
    "The interval has length of order $10^{-86}$; a grid with such a step would have about\n",
    "$5\\cdot10^{98}$ points on $[0,t_0]$. `float64` misses this interval and returns infinity: the true\n",
    "value of $G_3$ at the `float64` point is about $8.9\\cdot10^{532}$, which exceeds the range of this\n",
    "format. Let us plot $\\log_{10}G_3$ in a neighborhood of $t_0$ on the scale $10^{-86}$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f4ca4056",
   "metadata": {},
   "outputs": [],
   "source": [
    "xs = [mp.mpf(i) / 100 for i in range(-400, 401)]\n",
    "ys = [float(mp.log10(G(t0 + v * mp.mpf('1e-86'), 3))) for v in xs]\n",
    "fig, ax = plt.subplots(figsize=(8, 3.2))\n",
    "ax.plot([float(v) for v in xs], ys, color=kolory[3], lw=1.2)\n",
    "ax.axhline(0, color='crimson', lw=1, ls='--')\n",
    "ax.set_xlabel(r'$(t - t_0)\\cdot 10^{86}$')\n",
    "ax.set_ylabel(r'$\\log_{10} G_3(t)$')\n",
    "ax.set_title(r'Studnia wokół $t_0\\approx1{,}2566\\cdot10^{13}$; poniżej linii $A_3<0$',\n",
    "             fontsize=10)\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "788ae46f",
   "metadata": {},
   "source": [
    "Negative values exist, but on an interval of length of order $10^{-86}$ around $10^{13}$ —\n",
    "no grid or random sampling will find them, and `float64` cannot even represent $t_0$ with\n",
    "the required accuracy. We do not claim that $t_0$ is the smallest such point; it is the point\n",
    "indicated by the construction in the proof.\n",
    "\n",
    "## 6. A certificate for $a=42$\n",
    "\n",
    "The same construction, only around the 2019 solution. The weights at this point have about 171 digits,\n",
    "so the coordinates of $\\Gamma_3(t)$ must hit the target to within about $10^{-344}$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1caf11c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "m42 = rozwiazania[42]\n",
    "mp.mp.dps = 60\n",
    "M = sum((mp.mpf(v)**2 + 2)**3 for v in m42) + 42**2 + 2\n",
    "wagi42 = [38 * (mp.mpf(v)**2 + 2)**2 * M for v in m42]\n",
    "eps = 1 / (16 * mp.pi * max(wagi42)**2 * mp.sqrt(6))\n",
    "print(\"wagi:\", [mp.nstr(k, 4) for k in wagi42])\n",
    "print(\"szacowana potrzebna dokładność:\", mp.nstr(eps, 3))\n",
    "\n",
    "mp.mp.dps = 3300\n",
    "start = time.time()\n",
    "t42 = podnies3(m42, mp.mpf('1e-345'), mp.mpf('1e-345'))\n",
    "print(f\"czas konstrukcji: {time.time() - start:.0f} s;   t₀ ≈ {mp.nstr(t42, 15)}\")\n",
    "t42_napis = mp.nstr(t42, 2800)\n",
    "for dps in (3300, 4200):\n",
    "    mp.iv.dps = dps\n",
    "    I = G(mp.iv.mpf(t42_napis), 42, ctx=mp.iv)\n",
    "    gora = mp.nstr(mp.mpf(I.b.b), 6)\n",
    "    print(f\"{dps} cyfr: G_42(t₀) ≤ {gora};  A_42(t₀) < 0: {I.b < 1}\")\n",
    "for cyfry in (2750, 2770):\n",
    "    I = G(mp.iv.mpf(mp.nstr(t42, cyfry)), 42, ctx=mp.iv)\n",
    "    print(f\"t₀ z {cyfry} cyframi: A_42 < 0: {I.b < 1}\")\n",
    "przed = len(t42_napis.split('.')[0])\n",
    "print(f\"certyfikat: {przed} cyfr przed przecinkiem; początek: {t42_napis[:30]}…\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e93d7b4a",
   "metadata": {},
   "source": [
    "The certificate for $a=42$ is a number of order $10^{346}$ that has to be given to about 2770\n",
    "digits. The computer finds it in a minute — but only because we know a solution of the equation. Before\n",
    "September 2019 nobody could point to such a $t$, nor did anyone know whether it existed.\n",
    "\n",
    "## 7. $a=4$: a proof instead of numerics\n",
    "\n",
    "A sum of three cubes never leaves the residue $4$ modulo 9 (the cell in §2), so the equation for $a=4$\n",
    "has no solutions, and by Proposition P.1: **$A_4(t)>0$ for every $t\\in\\mathbb R$.** No sampling\n",
    "will prove this — after all, $A_3$ looked exactly the same. The question is settled by a three-line\n",
    "number-theoretic argument that numerics knows nothing about.\n",
    "\n",
    "## 8. $a=114$: we know the formula, not the answer\n",
    "\n",
    "We have $114\\equiv6\\pmod 9$, so the residue modulo 9 rules nothing out, and nobody has found a solution.\n",
    "So today **nobody knows whether $A_{114}(t)\\ge0$ for all $t$**.\n",
    "Heath-Brown's conjecture (1992) predicts that every integer not congruent to $4$ or $5$ modulo 9\n",
    "is a sum of three cubes (and in infinitely many ways). If it is right, $A_{114}$ is negative somewhere — at a place\n",
    "that today we cannot even estimate.\n",
    "\n",
    "```{admonition} Do we know the function $A_{114}$?\n",
    ":class: note\n",
    "Yes, completely. It is the formula from §1 for $a=114$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "A_{114}(t)&=256\\Bigl[\\bigl(u_1^3+u_2^3+u_3^3-114\\bigr)^2+\\sum_{i=1}^3\\sin^2(\\pi u_i)\\,k_i^4\\Bigr]-1,\\\\\n",
    "k_i&=38\\,(u_i^2+2)^2M,\\qquad M=\\sum_{j=1}^3(u_j^2+2)^3+12998,\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "where $s=t\\sin t^3$, $u_1=t\\sin t$, $u_2=s\\sin s$, $u_3=s\\sin s^3$. No solution of the\n",
    "equation appears in it — the machine from the proof uses only the polynomial $P_{114}$. We can compute\n",
    "the value $A_{114}(t)$ at any point with guaranteed accuracy (interval arithmetic, as\n",
    "in §5). The only thing we do not know is the answer to the question whether $A_{114}(t)<0$ for some $t$.\n",
    "\n",
    "A solution of the equation is not a component of the expression but a **certificate** of its negativity. If\n",
    "$A_{114}(t)<0$, then $f_{114}(\\Gamma_3(t))<1$, and then — as in the proof of Proposition P.1 —\n",
    "rounding the coordinates of $\\Gamma_3(t)$ to the nearest integers gives a solution of the\n",
    "equation $x_1^3+x_2^3+x_3^3=114$: the point on the curve is itself a witness (Remark 5.4 of the proof). Searching\n",
    "for $t$ with $A_{114}(t)<0$ is therefore searching for a solution. In §5–§6 we went the other way: from a known\n",
    "solution to $t_0$.\n",
    "```\n",
    "\n",
    "```{admonition} Does this prove Richardson's theorem?\n",
    ":class: warning\n",
    "No — and no single example will. Undecidability is a property of a **family**\n",
    "of questions: there is no algorithm that answers correctly for every expression. A single\n",
    "expression has a definite answer, so an algorithm that outputs it does exist: “print yes” or\n",
    "“print no” — although we may not know which. The family $A_a$ may not be enough either: if Heath-Brown's\n",
    "conjecture were true, the answer would depend only on $a\\bmod 9$, and would therefore be\n",
    "decidable. Undecidability requires the polynomial from the DPRM theorem (§1 and §11\n",
    "of the proof).\n",
    "\n",
    "A single case can exhibit practical difficulty ($a=3$, $a=42$), the limit of present-day\n",
    "knowledge ($a=114$), or unprovability. The last is produced by the same machine (§3–§6 and §11 of the proof)\n",
    "applied to another, enormous polynomial $Q$; denote the resulting expression by $A_Q$.\n",
    "\n",
    "* By the DPRM theorem there is a $Q$ for which the equation $Q=0$ has a solution in natural\n",
    "  numbers if and only if ZFC set theory is inconsistent. If ZFC is\n",
    "  consistent, then the statement “$A_Q(t)\\ge0$ for all $t$” is true but cannot be\n",
    "  proved in ZFC: the chain of equivalences from the proof can be carried out in ZFC, so such a proof\n",
    "  would yield a proof of the consistency of ZFC within ZFC itself, contrary to Gödel's second incompleteness theorem.\n",
    "* Davis, Matiyasevich and Robinson (1976) gave a $Q$ for which the equation $Q=0$ has no\n",
    "  solutions if and only if the Riemann hypothesis holds. Then “$A_Q\\ge0$ everywhere”\n",
    "  is equivalent to the Riemann hypothesis.\n",
    "\n",
    "The family $A_a$ shows something else: even when the general answer may be simple, **individual\n",
    "cases** can be extremely hard — and numerics cannot tell the easy ones from the hard ones.\n",
    "```\n",
    "\n",
    "## 9. The same question as a zero problem\n",
    "\n",
    "With the absolute value (§7 of the proof): $B_a=|A_a|-A_a$ is identically zero if and only if\n",
    "$A_a\\ge0$ everywhere. Hence $B_4\\equiv0$, $B_3\\not\\equiv0$, $B_{42}\\not\\equiv0$, and about $B_{114}$\n",
    "nobody knows. What will a computer algebra system say?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "570c845c",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Limit(Exception):\n",
    "    pass\n",
    "\n",
    "def z_limitem(f, sekundy):\n",
    "    \"\"\"Wywołuje f(), ale przerywa po zadanej liczbie sekund.\"\"\"\n",
    "    def stop(*_):\n",
    "        raise Limit\n",
    "    stary = signal.signal(signal.SIGALRM, stop)\n",
    "    signal.alarm(sekundy)\n",
    "    try:\n",
    "        return f()\n",
    "    except Limit:\n",
    "        return f\"(brak odpowiedzi po {sekundy} s)\"\n",
    "    finally:\n",
    "        signal.alarm(0)\n",
    "        signal.signal(signal.SIGALRM, stary)\n",
    "\n",
    "for a in (3, 4):\n",
    "    Aa = A_symb(a)\n",
    "    Ba = sp.Abs(Aa) - Aa\n",
    "    nieujemne, zero_B = Aa.is_nonnegative, Ba.is_zero\n",
    "    print(f\"a = {a}:  A.is_nonnegative = {nieujemne},  B.is_zero = {zero_B}\")\n",
    "    print(f\"        B.equals(0) = {z_limitem(lambda: Ba.equals(0), 5)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "583c47d2",
   "metadata": {},
   "source": [
    "SymPy honestly answers “I don't know” (`None`) or does not answer within 5 seconds — in the same way for both values of $a$,\n",
    "even though the answers are opposite.\n",
    "\n",
    "## 10. The moral\n",
    "\n",
    "* **Numerics sees only the points at which it computes.** The sign of $A_a$ depends on the arithmetic of\n",
    "  integers, which no finite sampling can see: the negative values live on\n",
    "  intervals of length $10^{-86}$ (for $a=3$) around $10^{13}$ — or farther out.\n",
    "* **Negativity can be certified by a finite computation; nonnegativity, in general, cannot.** A certificate ($t_0$ + interval\n",
    "  arithmetic) proves that $A_3<0$ and $A_{42}<0$ somewhere; this is exactly the semi-decidability of\n",
    "  Proposition 10.1. The positivity of $A_4$ requires a proof (modulo 9), and for $A_{114}$ there is no proof.\n",
    "* **Even an “easy yes” can be hard in practice:** the trivial $1^3+1^3+1^3=3$ yields a witness with about 100\n",
    "  digits, the solution for $42$ one with about 2770. Larger solutions — even worse.\n",
    "* Richardson's theorem says that no algorithm can cope with all such\n",
    "  questions. This example shows that the difficulty is not merely theoretical.\n",
    "\n",
    "## 11. Questions and exercises\n",
    "\n",
    "1. Why do both certificates begin with the digits $12566\\ldots$? *(Hint: what does\n",
    "   the construction in Lemma 4.2 start from?)*\n",
    "2. Which coordinate of $\\Gamma_3(t)$ changes fastest near $t_0$? Estimate its\n",
    "   derivative and explain where the interval length of order $10^{-86}$ comes from.\n",
    "3. Why does $t_0$ have to be known to about 100 digits, although $t_0\\approx10^{13}$?\n",
    "   Compare with the result in §5.\n",
    "4. $30=2220422932^3+(-2218888517)^3+(-283059965)^3$. Estimate (without computing the certificate) the order of\n",
    "   magnitude of $t_0$ and the number of digits needed. *(Hint: the weights grow like $|\\mathbf m|^{10}$.)*\n",
    "5. 💻 Compute the certificate for $a=29=3^3+1^3+1^3$ and compare it with $a=3$.\n",
    "6. 💻 Build the analogous expressions for the Pell equations $x^2-61y^2=-1$ (smallest positive\n",
    "   solution: $x=29718$, $y=3805$) and $x^2-61y^2=2$ (no solutions: $2$ is not a quadratic\n",
    "   residue modulo $61$). Compare the numerics and estimate $t_0$ for the first one.\n",
    "7. What would happen if the weights $k_i$ were replaced by ones? *(Cf. Example 3.1.)*\n",
    "\n",
    "**References.** A. R. Booker, *Cracking the problem with 33*, Research in Number Theory (2019),\n",
    "arXiv:1903.04284 · A. R. Booker, A. V. Sutherland, *On a question of Mordell*, Proc. Natl. Acad.\n",
    "Sci. USA 118 (2021), no. 11, doi:10.1073/pnas.2022377118, arXiv:2007.01209 (the solutions for $42$\n",
    "and new ones for $3$) · [Sums of three cubes](https://en.wikipedia.org/wiki/Sums_of_three_cubes)\n",
    "(Wikipedia; as of September 12, 2026, the open cases below 1000 are 114, 390, 627, 633, 732,\n",
    "921, and 975) · [Epoch AI: Sum of Three Cubes](https://epoch.ai/frontiermath/open-problems/sum-of-three-cubes)."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
