{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fa01673c",
   "metadata": {},
   "source": [
    "# The complete proof, step by step\n",
    "\n",
    "This chapter contains a complete proof of Richardson's theorem in the form given in the original paper\n",
    "(D. Richardson, *Some undecidable problems involving elementary functions of a real variable*,\n",
    "J. Symbolic Logic **33** (1968), 514–520), with the details filled in. Apart from standard theorems of analysis, the only facts\n",
    "taken without proof are the Davis–Putnam–Robinson theorem (and, in §11, Matiyasevich's theorem) and —\n",
    "only in the integration part — Liouville's theorem; see {doc}`r1_pojecia`. We have illustrated every step\n",
    "of the construction with a computation in Python.\n",
    "\n",
    "Print version: [the whole chapter in a single PDF file](https://bnaskrecki.faculty.wmi.amu.edu.pl/math-comp/en/pdf/richardson_pelny_dowod.pdf) (the same numbering, with the preliminaries, appendices and exercises)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7c1d2e3",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "# Komórka ukryta w książce: wykresy zapisujemy także jako PDF (wektorowo) dla wersji do druku.\n",
    "%config InlineBackend.figure_formats = ['png', 'pdf']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22832f22",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "import random\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": "ffe9ff9c",
   "metadata": {},
   "source": "## 0. The theorem and the plan of the proof\n\nRecall (Definition 3.2 in {doc}`r1_pojecia`): $\\mathcal A_1$ consists of the expressions in one variable\nbuilt from rational numbers, $\\pi$, $\\log 2$, the variable $x$, the operations $+,-,\\cdot$ and\nthe functions $\\exp$ and $\\sin$ (with arbitrary nesting); $\\mathcal B_1$ is the same with the absolute value $|\\cdot|$.\n\n```{admonition} Theorem R (Richardson, 1968 — concrete form)\n:class: important\n1. **(A — the sign problem.)** There is no algorithm that, for an arbitrary expression\n   $A\\in\\mathcal A_1$, decides whether $A(x)<0$ for some $x\\in\\mathbb R$.\n2. **(B — the zero/identity problem.)** There is no algorithm that, for an arbitrary expression\n   $B\\in\\mathcal B_1$, decides whether $B(x)=0$ for all $x\\in\\mathbb R$.\n3. **(C — the integration problem.)** There is no algorithm that, for an arbitrary $J\\in\\mathcal B_1$,\n   decides whether there exists $H\\in\\mathcal B_1$, differentiable on $\\mathbb R$, with $H'=J$.\n```\n\nIn §9 we give Richardson's original, more general formulation (arbitrary effectively given\nclasses of functions, including partial ones). All three parts follow from a single construction:\nfor a fixed undecidable set $U\\subseteq\\mathbb N$ we algorithmically build,\nfor each $a\\in\\mathbb N$, an expression $G_a\\in\\mathcal A_1$ satisfying a **dichotomy with a gap**\n\n$$\n\\begin{array}{ll}\na\\in U: & G_a\\ge 0 \\text{ everywhere and } \\inf_{t} G_a(t)=0,\\\\[2pt]\na\\notin U: & G_a(t)>1 \\text{ for every } t\\in\\mathbb R .\n\\end{array}\n$$\n\n| Step | Construction | Purpose |\n|---|---|---|\n| §1 | polynomial $P$ with powers $2^{x_i}$ | encode $a\\in U$ as the existence of an **integer** zero |\n| §2 | local majorants $k_i$ | control the change of $P^2$ under rounding, everywhere in space |\n| §3 | weighted penalty $f$, squared coordinates $F$ | “$f\\le1$” forces an integer zero — a **gap** between $0$ and $1$ |\n| §4 | curve $\\Gamma_n(t)$ from $t\\sin t$ and $t\\sin t^3$ | one variable, image dense in $\\mathbb R^n$ |\n| §5 | $G_a(t)=F(a,\\Gamma_n(t))$ | dichotomy in one variable |\n| §6–8 | $G_a-1$, absolute value, cutoff | sign, identity and integration problems |\n\nThe whole proof is a chain of equivalences, valid for every $a\\in\\mathbb N$:\n\n$$\n\\begin{aligned}\na\\in U\n&\\iff \\exists\\,\\mathbf m\\in\\mathbb N^n\\ \\ P(a,\\mathbf m)=0 &&\\text{(§1)}\\\\\n&\\iff \\exists\\,\\mathbf u\\in\\mathbb R^n\\ \\ F(a,\\mathbf u)=0 &&\\text{(§3)}\\\\\n&\\iff \\exists\\,t\\in\\mathbb R\\ \\ G_a(t)<1 &&\\text{(§4–5)}\\\\\n&\\iff A_a=G_a-1 \\text{ is negative somewhere} &&\\text{(§6)}\\\\\n&\\iff B_a=|A_a|-A_a\\not\\equiv 0 &&\\text{(§7)}\\\\\n&\\iff J_a=e^{x^2}S_a \\text{ has no antiderivative in } \\mathcal B_1 &&\\text{(§8)}.\n\\end{aligned}\n$$\n\n## 1. The arithmetic input\n\n```{admonition} Theorem 1.1 (Davis–Putnam–Robinson in the form used by Richardson; external)\n:class: important\nThere exist $n\\ge 2$ and a polynomial $p(Y,X_1,\\dots,X_n,Z_1,\\dots,Z_n)$ with integer coefficients\nsuch that for\n\n$$\nP(y,\\mathbf x)=p\\bigl(y,\\,x_1,\\dots,x_n,\\,2^{x_1},\\dots,2^{x_n}\\bigr)\n$$\n\nthe set\n\n$$\nU=\\{\\,a\\in\\mathbb N:\\ \\exists\\,\\mathbf m\\in\\mathbb N^n\\ \\ P(a,\\mathbf m)=0\\,\\}\n$$\n\nis undecidable.\n```\n\nThis follows from Theorem 2.3 in {doc}`r1_pojecia`: exponentiation with an arbitrary base,\n$c=a^b$, can be expressed through powers of two (proof in {doc}`r3_dodatki`, Appendix A), and a system of\nequations $E_1=\\dots=E_r=0$ is equivalent to the single equation $\\sum E_j^2=0$. “Dummy”\nvariables allow us to assume $n\\ge2$. The polynomial $p$ is **fixed once and for all**; only $a$ varies.\n\nWe use the polynomial $P$ only through two properties:\n\n* **(P1)** $P\\in\\mathcal A_{n+1}$, since $2^{x}=\\exp\\bigl(x\\log 2\\bigr)$ — hence the constant $\\log 2$ in the language;\n* **(P2)** $P(a,\\mathbf m)\\in\\mathbb Z$ for $a\\in\\mathbb N$, $\\mathbf m\\in\\mathbb N^n$; in particular\n\n  $$\n  0\\le P(a,\\mathbf m)^2<1\\ \\Longrightarrow\\ P(a,\\mathbf m)=0 .\n  $$\n\nProperty (P2) is the only place where the *discreteness* of the integers comes into play: a small\napproximate zero becomes an exact zero.\n\n```{admonition} Remark 1.2 (on the constant $\\pi$)\n:class: note\nIn his definition of “subelementary” expressions, Richardson (p. 515) does not list $\\pi$, although he\nimmediately uses $\\sin(\\pi x_i)$, and $\\pi$ appears in the hypotheses of the main theorem. We include $\\pi$\nfrom the start. Thanks to this, $\\cos u=\\sin(u+\\pi/2)$ and derivatives remain in the language (Lemma 2.3).\n```\n\n```{admonition} Remark 1.3 (where $\\log 2$ and $\\exp$ come from)\n:class: note\nThe function $\\exp$ and the constant $\\log 2$ are needed **only** to write $2^{x_i}$, that is, only\nbecause in 1968 the undecidability of *exponential* Diophantine equations was known.\nAfter Matiyasevich's theorem (1970) one can take an ordinary polynomial, and then the whole construction\ndoes without $\\exp$ and $\\log 2$ — see §11.\n```\n\n## 2. Local majorants\n\nWe are going to round real points to integer points, and we must control how $P^2$ changes\nin the process. The points may lie arbitrarily far away, so a bound on the derivative on a single\ncompact set is not enough: we need a **formula** — an expression that, at every point,\nbounds the function on a whole neighborhood of that point.\n\n```{admonition} Lemma 2.1 (local majorants; Richardson, *Lemma One*)\n:class: important\nFor every expression $A\\in\\mathcal A_d$ one can algorithmically construct $M_A\\in\\mathcal A_d$ such\nthat for every $\\mathbf z\\in\\mathbb R^d$\n\n$$\nM_A(\\mathbf z)>1\n\\qquad\\text{and}\\qquad\n|A(\\mathbf z+\\boldsymbol\\eta)|<M_A(\\mathbf z)\\quad\\text{for every } \\boldsymbol\\eta \\text{ with } \\lVert\\boldsymbol\\eta\\rVert_\\infty\\le 1 .\n$$\n\n```\n\n**Proof.** We define $M_A$ recursively on the expression tree of $A$:\n\n$$\n\\begin{aligned}\nM_c &= c^2+2 \\quad(c \\text{ — a constant: } q\\in\\mathbb Q,\\ \\pi,\\ \\log 2), &\nM_{x_j} &= x_j^2+2,\\\\\nM_{A\\pm B} &= M_A+M_B, &\nM_{A\\cdot B} &= M_A\\,M_B,\\\\\nM_{\\exp A} &= \\exp(M_A), &\nM_{\\sin A} &= 2 .\n\\end{aligned}\n$$\n\nEach right-hand side belongs to $\\mathcal A_d$, and the recursion terminates because the tree is finite.\nWe verify both properties by induction on the structure of the expression; fix $\\mathbf z$ and\n$\\boldsymbol\\eta$ with $\\lVert\\boldsymbol\\eta\\rVert_\\infty\\le1$.\n\n* *A constant $c$.* The value does not depend on the point, and\n  $c^2+2-|c|=\\bigl(|c|-\\tfrac12\\bigr)^2+\\tfrac74>0$, so $|c|<c^2+2$; obviously $c^2+2\\ge2>1$.\n* *A variable $x_j$.* $|z_j+\\eta_j|\\le|z_j|+1<z_j^2+2$, since\n  $z_j^2+2-(|z_j|+1)=\\bigl(|z_j|-\\tfrac12\\bigr)^2+\\tfrac34>0$.\n* *Sum and difference.* By the triangle inequality,\n  $|A\\pm B|\\le|A|+|B|<M_A+M_B$ (values at $\\mathbf z+\\boldsymbol\\eta$, majorants at $\\mathbf z$);\n  the sum of the majorants exceeds $2$.\n* *Product.* $|AB|=|A|\\,|B|<M_A M_B$, since both majorants are positive; a product of numbers $>1$ is $>1$.\n* *Exponential.* $e^{A}\\le e^{|A|}<e^{M_A}$ by monotonicity, and $e^{M_A}>e>1$.\n* *Sine.* $|\\sin A|\\le1<2$. $\\blacksquare$\n\nThe construction never asks for the sign or the value of any expression. For the constants of the grammar ($q$,\n$\\pi$, $\\log 2$) the sign is known, so $|c|+2$ would also work, as in the original. We take $c^2+2$ because\nthis rule also works without change for any variable-free subexpression treated as a constant\n(this is what the function `majoranta` below does), e.g., $\\pi-\\tfrac{22}{7}$, whose sign the algorithm need not\nbe able to decide. Here is an implementation on\nSymPy trees:"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "92b6bc3b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def majoranta(e):\n",
    "    \"\"\"Majoranta lokalna M_e (Lemat 2.1) zbudowana rekurencyjnie po drzewie wyrażenia SymPy.\"\"\"\n",
    "    if e.is_number:                       # stała: liczba wymierna, π, log 2, ...\n",
    "        return e**2 + 2\n",
    "    if e.is_Symbol:                       # zmienna\n",
    "        return e**2 + 2\n",
    "    if e.is_Add:\n",
    "        return sp.Add(*[majoranta(a) for a in e.args])\n",
    "    if e.is_Mul:                          # SymPy zapisuje A - B jako A + (-1)·B\n",
    "        return sp.Mul(*[majoranta(a) for a in e.args])\n",
    "    if e.is_Pow and e.exp.is_Integer and e.exp > 0:\n",
    "        return majoranta(e.base) ** e.exp  # potęga = wielokrotny iloczyn\n",
    "    if isinstance(e, sp.exp):\n",
    "        return sp.exp(majoranta(e.args[0]))\n",
    "    if isinstance(e, (sp.sin, sp.cos)):   # cos u = sin(u + π/2)\n",
    "        return sp.Integer(2)\n",
    "    raise ValueError(f\"węzeł spoza języka: {e.func}\")\n",
    "\n",
    "u, v = sp.symbols('u v')\n",
    "A = sp.exp(u*v) - sp.sin(u)\n",
    "M = majoranta(A)\n",
    "M"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3023d8a",
   "metadata": {},
   "source": [
    "Lemma 2.1 promises the inequality $|A(\\mathbf z+\\boldsymbol\\eta)|<M_A(\\mathbf z)$ for every\n",
    "shift with $\\lVert\\boldsymbol\\eta\\rVert_\\infty\\le1$. Let us check it on $20{,}000$ random pairs\n",
    "$(\\mathbf z,\\boldsymbol\\eta)$ and count the violations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7f2bfbdd",
   "metadata": {},
   "outputs": [],
   "source": [
    "fA = sp.lambdify((u, v), A, 'math')\n",
    "fM = sp.lambdify((u, v), M, 'math')\n",
    "random.seed(0)\n",
    "naruszenia = 0\n",
    "for _ in range(20_000):\n",
    "    z = (random.uniform(-1.5, 1.5), random.uniform(-1.5, 1.5))\n",
    "    eta = (random.uniform(-1, 1), random.uniform(-1, 1))\n",
    "    if not abs(fA(z[0] + eta[0], z[1] + eta[1])) < fM(*z):\n",
    "        naruszenia += 1\n",
    "naruszenia"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "866b17b7",
   "metadata": {},
   "source": "No violations — as it should be: the lemma has been proved, and the test merely illustrates it.\nThe result $\\exp\\bigl((u^2+2)(v^2+2)\\bigr)+6$ (rather than $+2$) comes from the fact that SymPy stores\n$-\\sin u$ as the product $(-1)\\cdot\\sin u$, and the product rule gives $3\\cdot2$. This is still a valid\nmajorant. More generally:\n\n```{admonition} Remark 2.2 (the majorant depends on the notation)\n:class: note\n$M_A$ is a function of the **tree** $A$, not of the function that $A$ denotes: the trees $x-x$ and $0$ get\nthe majorants $2(x^2+2)$ and $2$ (SymPy would simplify $x-x$ to $0$ already when building the tree). This does no harm — the reduction needs\n*some* proven bound given by a formula, not the best one.\n```\n\n```{admonition} Lemma 2.3 (effective differentiation)\n:class: important\nFor $A\\in\\mathcal A_d$, an expression for $\\partial A/\\partial x_j$ in the language $\\mathcal A_d$ can be\nconstructed algorithmically.\n```\n\n**Proof.** Recursively: $\\partial_j c=0$, $\\partial_j x_i\\in\\{0,1\\}$, the sum and product rules,\n$\\partial_j e^{A}=e^{A}\\partial_jA$ and\n$\\partial_j\\sin A=\\sin\\!\\bigl(A+\\tfrac{\\pi}{2}\\bigr)\\,\\partial_jA$. $\\blacksquare$\n\n```{admonition} Definition 2.4 (weights)\n:class: note\nLet $Q(y,\\mathbf x)=P(y,\\mathbf x)^2$. For $i=1,\\dots,n$ we set\n$k_i=M_{\\partial Q/\\partial x_i}$ (Lemma 2.1 applied to the expression from Lemma 2.3, in the variables\n$(y,x_1,\\dots,x_n)$, with zero perturbation of $y$). Then $k_i\\in\\mathcal A_{n+1}$, $k_i>1$, and\n\n$$\n\\left|\\frac{\\partial Q}{\\partial x_i}(y,\\mathbf z)\\right| < k_i(y,\\mathbf x)\n\\qquad\\text{whenever } \\lVert\\mathbf z-\\mathbf x\\rVert_\\infty\\le 1. \\tag{2.1}\n$$\n\n```\n\nNote: the derivative is evaluated at the point $\\mathbf z$, while the weight is evaluated at the **center** $\\mathbf x$.\nA single weight controls the derivative on the whole cube around $\\mathbf x$.\n\n## 3. The weighted penalty and the rounding theorem\n\nOn the set $[0,\\infty)^n$, the zeros of the expression $P(y,\\mathbf x)^2+\\sum_i\\sin^2(\\pi x_i)$ are exactly\nthe integer solutions (since $\\sin(\\pi x)=0\\iff x\\in\\mathbb Z$). Later, however, we will replace\nthe variables by the points of a dense curve, which **comes arbitrarily close** to a zero but need not\nhit it. So we need a theorem about **small values**, not only about zeros.\nThe naive residual does not provide one:\n\n```{admonition} Example 3.1 (no gap without weights)\n:class: note\nFor $N\\ge2$ let $P_N(x)=Nx-1$: there is no root in $\\mathbb N$. And yet\n$P_N(1/N)^2+\\sin^2(\\pi/N)=\\sin^2(\\pi/N)\\to0$ as $N\\to\\infty$. No fixed threshold separates\n“yes” from “no” across the whole family: the polynomial becomes more and more sensitive to perturbations.\n```\n\nLet us compare, in a plot, the unweighted residual with the weighted penalty $f$ (Definition 3.2 below, here with $n=1$) for\n$N=5$ and $N=20$:"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f32263d",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = sp.symbols('x')\n",
    "xs = np.linspace(0, 1.25, 40_001)\n",
    "fig, ax = plt.subplots(figsize=(7.5, 3.4))\n",
    "for N, kolor in ((5, '#d97706'), (20, '#4f46e5')):\n",
    "    P = N*x - 1\n",
    "    k = majoranta(sp.factor(sp.diff(P**2, x)))          # waga z Lematu 2.1\n",
    "    r = sp.lambdify(x, P**2 + sp.sin(sp.pi*x)**2, 'numpy')\n",
    "    f = sp.lambdify(x, 2**4 * (P**2 + sp.sin(sp.pi*x)**2 * k**4), 'numpy')\n",
    "    ax.semilogy(xs, r(xs), color=kolor, lw=1.2, label=f\"bez wag, N={N}: min = {r(xs).min():.4f}\")\n",
    "    ax.semilogy(xs, f(xs), color=kolor, lw=1.2, ls='--', label=f\"kara ważona f, N={N}: min = {f(xs).min():.0f}\")\n",
    "ax.axhline(1, color='black', lw=0.8)\n",
    "ax.set_xlabel('x'); ax.legend(fontsize=8, loc='upper right'); ax.set_ylim(1e-3, 1e30)\n",
    "ax.set_title('Residuum bez wag schodzi do zera, kara ważona zostaje powyżej 1')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1997c316",
   "metadata": {},
   "source": "Without weights, the minimum of the residual drops from $0.27$ ($N=5$) to $0.024$ ($N=20$), while in both\ncases the weighted penalty has minimum $16$ (at $x=0$, where $P_N(0)^2=1$), far above the threshold $1$.\n\n```{admonition} Definition 3.2 (weighted penalty; Richardson, p. 516)\n:class: note\n\n$$\nf(y,\\mathbf x)=(n+1)^4\\Bigl[\\,P(y,\\mathbf x)^2+\\sum_{i=1}^n\\sin^2(\\pi x_i)\\,k_i(y,\\mathbf x)^4\\Bigr].\n$$\n\nThis is an expression in $\\mathcal A_{n+1}$, nonnegative everywhere. The term $P^2$ measures the error in the equation,\nthe sine terms measure the distance from the lattice $\\mathbb Z^n$; the larger the derivatives of $P^2$\nat a given place, the closer to the lattice the weights require the point to be.\n```\n\n```{admonition} Lemma 3.3 (the sine measures the distance to an integer)\n:class: important\nLet $x\\ge0$, let $m\\in\\mathbb N$ be the natural number nearest to $x$ (either one in case of a tie), and\n$d=|x-m|$. Then $0\\le d\\le\\tfrac12$, $|\\sin(\\pi x)|=\\sin(\\pi d)$, and\n\n$$\n2d\\le|\\sin(\\pi x)|\\qquad\\text{and consequently}\\qquad d\\le\\bigl(\\sin^2(\\pi x)\\bigr)^{1/4}.\n$$\n\n```\n\n**Proof.** The periodicity and symmetry of the sine give $|\\sin(\\pi x)|=|\\sin(\\pi(x-m))|=\\sin(\\pi d)$, since\n$0\\le\\pi d\\le\\pi/2$. On $[0,\\tfrac12]$ the function $t\\mapsto\\sin(\\pi t)$ is concave\n(its second derivative is $-\\pi^2\\sin(\\pi t)\\le0$), so it lies above the chord joining $(0,0)$ and\n$(\\tfrac12,1)$: $\\sin(\\pi d)\\ge2d$. Since $d\\le\\tfrac12\\le2$, we have $2d\\ge d^2$; hence\n$d^2\\le\\sin(\\pi d)=|\\sin(\\pi x)|$, and taking square roots, $d\\le|\\sin\\pi x|^{1/2}=(\\sin^2\\pi x)^{1/4}$.\n$\\blacksquare$\n\n(Richardson proves $t^2\\le\\sin(\\pi t)$ on $[0,\\tfrac12]$ by studying the function\n$\\sin(\\pi t)-t^2$; the concavity argument is shorter.)\n\n```{admonition} Theorem 3.4 (rounding theorem; Richardson, Theorem One)\n:class: important\nFor every $a\\in\\mathbb N$ the following conditions are equivalent:\n1. $\\exists\\,\\mathbf m\\in\\mathbb N^n\\ \\ P(a,\\mathbf m)=0$ (i.e., $a\\in U$);\n2. $\\exists\\,\\mathbf x\\in[0,\\infty)^n\\ \\ f(a,\\mathbf x)=0$;\n3. $\\exists\\,\\mathbf x\\in[0,\\infty)^n\\ \\ f(a,\\mathbf x)\\le1$.\n\nIn particular, if $a\\notin U$, then $f(a,\\mathbf x)>1$ at every point $\\mathbf x\\ge0$.\n```\n\n**Proof.** (1)⇒(2): at an integer zero $\\mathbf m$, both $P$ and all the $\\sin(\\pi m_i)$ vanish.\n(2)⇒(3) is obvious. It remains to prove (3)⇒(1). Let $\\mathbf x\\ge0$ and $f(a,\\mathbf x)\\le1$.\n\n*Step 1 (each term is small).* All the terms in the brackets are nonnegative, so\n\n$$\nQ(a,\\mathbf x)\\le\\frac1{(n+1)^4},\\qquad\n\\sin^2(\\pi x_i)\\,k_i(a,\\mathbf x)^4\\le\\frac1{(n+1)^4}\\quad(i=1,\\dots,n).\n$$\n\nTaking fourth roots (the weights are positive) gives\n$\\bigl(\\sin^2(\\pi x_i)\\bigr)^{1/4}k_i(a,\\mathbf x)\\le\\frac1{n+1}$.\n\n*Step 2 (rounding).* Let $m_i$ be the natural number nearest to $x_i$, and\n$d_i=|m_i-x_i|\\le\\frac12$. By Lemma 3.3,\n\n$$\nd_i\\,k_i(a,\\mathbf x)\\le\\frac1{n+1}\\qquad(i=1,\\dots,n). \\tag{3.1}\n$$\n\n*Step 3 (estimating along the whole segment).* Let $\\gamma(t)=\\mathbf x+t(\\mathbf m-\\mathbf x)$,\n$t\\in[0,1]$. Every point of the segment lies at distance $\\le\\frac12$ from $\\mathbf x$ in the maximum norm,\nso (2.1) applies. By Theorem 4.4 in {doc}`r1_pojecia`:\n\n$$\nQ(a,\\mathbf m)-Q(a,\\mathbf x)=\\int_0^1\\sum_{i=1}^n(m_i-x_i)\\,\\frac{\\partial Q}{\\partial x_i}(a,\\gamma(t))\\,dt\n\\le\\sum_{i=1}^n d_i\\,k_i(a,\\mathbf x).\n$$\n\nHence, by Step 1 and (3.1),\n\n$$\n0\\le Q(a,\\mathbf m)\\le\\frac1{(n+1)^4}+\\frac{n}{n+1}<1 , \\tag{3.2}\n$$\n\nwhere the last inequality is strict because $(n+1)^{-4}<(n+1)^{-1}$.\n\n*Step 4 (integrality).* Since $a\\in\\mathbb N$ and $\\mathbf m\\in\\mathbb N^n$, by (P2)\nthe number $Q(a,\\mathbf m)=P(a,\\mathbf m)^2$ is a nonnegative integer less than $1$, i.e., $0$.\nHence $P(a,\\mathbf m)=0$. $\\blacksquare$\n\n```{admonition} Division of labor in the proof\n:class: tip\nNonnegative coordinates round to **natural** numbers (this matters, since $2^{x}$ is not an integer\nfor negative integers). The weights control the whole segment, not just its endpoints.\nThe factor $(n+1)^4$ leaves a margin below $1$. Integrality enters only in the last\nstep, where an approximate zero becomes an exact one.\n```\n\n```{admonition} Remark 3.5 (a variant with squares)\n:class: note\nThe same weights work in the simpler penalty\n$f_{\\mathrm{alt}}=(n+1)^2\\bigl[P^2+\\sum_i\\sin^2(\\pi x_i)k_i^2\\bigr]$: from $f_{\\mathrm{alt}}\\le1$\nand the stronger inequality $2d_i\\le|\\sin\\pi x_i|$ we get $d_ik_i\\le\\frac1{2(n+1)}$, so\n$Q(a,\\mathbf m)\\le(n+1)^{-2}+\\frac{n}{2(n+1)}<1$. In what follows we stick to Richardson's\nfourth powers.\n```\n\n```{admonition} Remark 3.6 (the gap is even uniform)\n:class: note\nIf $f(a,\\mathbf x)\\le s$, the same computation gives\n$Q(a,\\mathbf m)\\le\\varphi(s)=\\frac{s}{(n+1)^4}+\\frac{n\\,s^{1/4}}{n+1}$. Since\n$\\varphi(1)<1$ and $\\varphi$ is continuous, there is $s_0>1$ (depending only on $n$) with\n$\\varphi(s_0)<1$. Then for $a\\notin U$ we have $f(a,\\cdot)>s_0$, i.e., $\\inf f\\ge s_0>1$.\nThis strengthened version is not needed later.\n```\n\nThe last step of this part removes the constraint $\\mathbf x\\ge0$: squares range over the entire\nset $[0,\\infty)^n$.\n\n```{admonition} Corollary 3.7 (the gap on all of $\\mathbb R^n$; Richardson, Corollary)\n:class: important\nLet $F(y,u_1,\\dots,u_n)=f(y,u_1^2,\\dots,u_n^2)$. Then $F\\in\\mathcal A_{n+1}$, $F\\ge0$, and for\n$a\\in\\mathbb N$:\n* if $a\\in U$, then $F(a,\\mathbf u)=0$ for some $\\mathbf u\\in\\mathbb R^n$;\n* if $a\\notin U$, then $F(a,\\mathbf u)>1$ for **every** $\\mathbf u\\in\\mathbb R^n$.\n\nEquivalently: $a\\in U\\iff\\exists\\mathbf u\\ F(a,\\mathbf u)=0\\iff\\exists\\mathbf u\\ F(a,\\mathbf u)<1\n\\iff\\exists\\mathbf u\\ F(a,\\mathbf u)\\le1$.\n```\n\n**Proof.** The map $\\mathbf u\\mapsto(u_1^2,\\dots,u_n^2)$ maps $\\mathbb R^n$\n**onto** $[0,\\infty)^n$ (a witness for $\\mathbf m$ is $u_i=\\sqrt{m_i}$). The claim follows\nfrom Theorem 3.4. Square roots appear only in the proof; the expression $F$ contains\nonly squares. $\\blacksquare$\n\n## 4. One variable suffices: a dense curve\n\nWe now have an undecidable inequality in $n$ variables. Richardson replaces all the variables\nby functions of **one** variable, using two oscillations at different scales:\n\n$$\nh(t)=t\\sin t,\\qquad g(t)=t\\sin(t^3).\n$$\n\nThe idea: near a large $v$, on an interval of length of order $\\delta/v$, the function $h$ changes\nby at most $\\delta$ (since $|h'(t)|\\le1+t$), while the phase $t^3$ changes by about $3v^2\\cdot\\delta/v=3\\delta v$\n— arbitrarily much. So $h$ barely moves, while $g$ (with amplitude $\\approx v$) sweeps\nthe whole interval $[-v,v]$.\n\n```{admonition} Lemma 4.1 (arbitrarily distant solutions of $h(v)=a$)\n:class: important\nFor every $a\\in\\mathbb R$ and $L>0$ there is $v>L$ with $h(v)=a$.\n```\n\n**Proof.** Choose $k\\in\\mathbb N$ so large that $p=2\\pi k+\\frac\\pi2>\\max\\{L,|a|\\}$, and let\n$q=2\\pi k+\\frac{3\\pi}2$. Then $h(p)=p>a$ and $h(q)=-q<a$, so by the intermediate value theorem\n$h(v)=a$ for some $v\\in(p,q)$; clearly $v>L$. $\\blacksquare$\n\n```{admonition} Lemma 4.2 (lifting: one coordinate approximate, the other exact; Richardson, *Lemmas Two* and *Three*)\n:class: important\nFor any $a,b\\in\\mathbb R$, $\\delta>0$ and $M\\ge0$ there is $w>M$ such that\n\n$$\n|h(w)-a|<\\delta\\qquad\\text{and}\\qquad g(w)=b .\n$$\n\n```\n\n**Proof.** Choose $R>\\max\\{M,\\,|b|,\\,1,\\,4\\pi/\\delta\\}$. By Lemma 4.1 we take\n$v>\\sqrt{R^2+\\delta/2}$ with $h(v)=a$ and set $u=\\sqrt{v^2-\\delta/2}$. Then $v>u>R$ and\n$v^2-u^2=\\delta/2$.\n\n*The interval $[u,v]$ is short for $h$.* Since $u>1$,\n\n$$\n(v-u)(v+1)<(v-u)(v+u)=\\tfrac{\\delta}{2}<\\delta . \\tag{4.1}\n$$\n\n*On it, the phase $t^3$ changes by more than a period.* Using $v^2=u^2+\\delta/2$:\n\n$$\nv^3-u^3=v\\,(u^2+\\tfrac\\delta2)-u^3=u^2(v-u)+\\tfrac\\delta2\\,v>\\tfrac\\delta2\\,u>\\tfrac\\delta2\\,R>2\\pi . \\tag{4.2}\n$$\n\n*$g$ passes through $b$.* The open interval $(u^3,v^3)$ has length $>2\\pi$, so it contains\na number $\\theta_+\\equiv\\frac\\pi2$ and a number $\\theta_-\\equiv\\frac{3\\pi}2\\pmod{2\\pi}$ (both\nprogressions have step $2\\pi$). Their cube roots $t_\\pm=\\theta_\\pm^{1/3}$ lie in $(u,v)$ and\n\n$$\ng(t_+)=t_+>u>|b|\\ge b,\\qquad g(t_-)=-t_-<-u<-|b|\\le b .\n$$\n\nBy the intermediate value theorem there is $w$ between $t_+$ and $t_-$ (so $w\\in(u,v)$, $w>M$) with $g(w)=b$.\n\n*$h$ stays close to $a$.* For $s\\in[u,v]$: $|h'(s)|=|\\sin s+s\\cos s|\\le1+s\\le1+v$.\nBy the mean value theorem and (4.1),\n\n$$\n|h(w)-a|=|h(w)-h(v)|\\le(v-w)(1+v)\\le(v-u)(1+v)<\\delta . \\qquad\\blacksquare\n$$\n\nThis proof is constructive and can be carried out numerically. Since the phase $t^3$ is\nhuge, we compute in high-precision arithmetic (`mpmath`, 80 digits):"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27b942e8",
   "metadata": {},
   "outputs": [],
   "source": [
    "mp.mp.dps = 80\n",
    "h = lambda t: t * mp.sin(t)\n",
    "g = lambda t: t * mp.sin(t**3)\n",
    "\n",
    "def bisekcja(F, lo, hi, kroki=400):\n",
    "    \"\"\"Miejsce zerowe F na [lo, hi], gdy F(lo), F(hi) mają różne znaki (tw. Darboux).\"\"\"\n",
    "    flo = F(lo)\n",
    "    for _ in range(kroki):\n",
    "        mid = (lo + hi) / 2\n",
    "        if (F(mid) > 0) == (flo > 0):\n",
    "            lo, flo = mid, F(mid)\n",
    "        else:\n",
    "            hi = mid\n",
    "    return (lo + hi) / 2\n",
    "\n",
    "def podnies(a, b, delta, M=0):\n",
    "    \"\"\"Lemat 4.2: zwraca w > M z |h(w) - a| < delta i g(w) = b — dokładnie według dowodu.\"\"\"\n",
    "    a, b, delta = mp.mpf(a), mp.mpf(b), mp.mpf(delta)\n",
    "    R = max(mp.mpf(M), abs(b), mp.mpf(1), 4 * mp.pi / delta) * (1 + mp.mpf('1e-9'))\n",
    "    dolna = mp.sqrt(R**2 + delta / 2)                        # chcemy v > sqrt(R^2 + δ/2)\n",
    "    k = int(mp.ceil((max(dolna, abs(a)) - mp.pi / 2) / (2 * mp.pi))) + 1\n",
    "    v = bisekcja(lambda t: h(t) - a, 2*mp.pi*k + mp.pi/2, 2*mp.pi*k + 3*mp.pi/2)   # Lemat 4.1\n",
    "    u = mp.sqrt(v**2 - delta / 2)\n",
    "    assert (v - u) * (v + 1) < delta / 2 and v**3 - u**3 > 2 * mp.pi          # (4.1), (4.2)\n",
    "    nastepna = lambda c: c + 2 * mp.pi * mp.ceil((u**3 - c) / (2 * mp.pi))     # pierwsza ≡ c (mod 2π) > u^3\n",
    "    t_plus, t_minus = mp.cbrt(nastepna(mp.pi / 2)), mp.cbrt(nastepna(3 * mp.pi / 2))\n",
    "    w = bisekcja(lambda t: g(t) - b, min(t_plus, t_minus), max(t_plus, t_minus))\n",
    "    return w, dict(R=R, u=u, v=v)\n",
    "\n",
    "w, info = podnies(3, -2, 0.1)\n",
    "print(f\"w = {mp.nstr(w, 20)}\")\n",
    "print(f\"|h(w) - 3| = {mp.nstr(abs(h(w) - 3), 6)}  (< δ = 0.1)\")\n",
    "print(f\"g(w) - (-2) = {mp.nstr(g(w) + 2, 6)}\")\n",
    "print(f\"długość przedziału v - u = {mp.nstr(info['v'] - info['u'], 6)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61f209bb",
   "metadata": {},
   "source": [
    "We obtained $w\\approx135.07$: $|h(w)-3|\\approx0.02<\\delta$, while $g(w)$ differs from $-2$ by about\n",
    "$4\\cdot10^{-73}$, i.e., at the limit of the working precision. On the interval $[u,v]$, of length about\n",
    "$1.85\\cdot10^{-4}$, the function $h$ barely moves, while $g$ performs more than one and a half oscillations\n",
    "with amplitude about $v$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85f5041f",
   "metadata": {},
   "outputs": [],
   "source": [
    "ts = [info['u'] + (info['v'] - info['u']) * j / 2000 for j in range(2001)]\n",
    "fig, (a1, a2) = plt.subplots(1, 2, figsize=(9, 3))\n",
    "a1.plot([float(t - info['u']) for t in ts], [float(h(t)) for t in ts], color='#d97706')\n",
    "a1.axhline(3, color='black', lw=0.6); a1.set_title('h(t) = t sin t na [u, v]'); a1.set_xlabel('t − u')\n",
    "a2.plot([float(t - info['u']) for t in ts], [float(g(t)) for t in ts], color='#4f46e5', lw=0.8)\n",
    "a2.axhline(-2, color='black', lw=0.6); a2.set_title('g(t) = t sin t³ na [u, v]'); a2.set_xlabel('t − u')\n",
    "plt.tight_layout(); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a349c677",
   "metadata": {},
   "source": "Now we assemble the curve in $\\mathbb R^n$. We write $g^{[j]}$ for the $j$-fold **composition** of $g$\n(not a power), $g^{[0]}(t)=t$.\n\n```{admonition} Definition 4.3 (the Richardson curve)\n:class: note\nFor $n\\ge2$:\n\n$$\n\\Gamma_n(t)=\\Bigl(h(t),\\ h\\bigl(g(t)\\bigr),\\ \\dots,\\ h\\bigl(g^{[n-2]}(t)\\bigr),\\ g^{[n-1]}(t)\\Bigr).\n$$\n\nThe first $n-1$ coordinates begin with $h$, the last one is an iterate of $g$ alone; e.g.,\n$\\Gamma_2=(h,g)$, $\\Gamma_4=\\bigl(h(t),h(g(t)),h(g(g(t))),g(g(g(t)))\\bigr)$. The following\nrecursion holds:\n\n$$\n\\Gamma_{n+1}(t)=\\bigl(h(t),\\ \\Gamma_n(g(t))\\bigr). \\tag{4.3}\n$$\n\n```\n\n```{admonition} Theorem 4.4 (density with an exact last coordinate; Richardson, Theorem Two)\n:class: important\nFor $n\\ge2$, $\\mathbf a\\in\\mathbb R^n$, $\\delta>0$ and $M\\ge0$ there is $w>M$ such that\n\n$$\n\\bigl|h\\bigl(g^{[j-1]}(w)\\bigr)-a_j\\bigr|<\\delta\\quad(1\\le j\\le n-1),\\qquad g^{[n-1]}(w)=a_n .\n$$\n\nIn particular, the set $\\Gamma_n\\bigl((M,\\infty)\\bigr)$ is dense in $\\mathbb R^n$.\n```\n\n**Proof.** Induction on $n$. For $n=2$ this is Lemma 4.2. Assume the claim for $n$ and take a target\n$(a_1,\\dots,a_{n+1})$. The induction hypothesis for the “tail” $(a_2,\\dots,a_{n+1})$ (with $M=0$)\ngives $w^*>0$ for which the first $n-1$ coordinates of $\\Gamma_n(w^*)$ approximate\n$a_2,\\dots,a_n$ to within $\\delta$, and the last one equals $a_{n+1}$. Lemma 4.2 with targets\n$a_1$ and $w^*$ gives $w>M$ with $|h(w)-a_1|<\\delta$ and $g(w)=w^*$. By (4.3),\n$\\Gamma_{n+1}(w)=\\bigl(h(w),\\Gamma_n(w^*)\\bigr)$ — exactly the required approximation.\nDensity: every nonempty open set contains a cube $\\{\\mathbf u:\\lVert\\mathbf u-\\mathbf a\\rVert_\\infty<\\delta\\}$.\n$\\blacksquare$\n\n```{admonition} Remark 4.5 (why the last coordinate is exact)\n:class: tip\nThe induction step requires $g(w)=w^*$ **exactly**. If we only had $g(w)\\approx w^*$, the error\nwould be amplified by the very steeply varying iterates of $g$; it could be controlled only by a separate\nargument based on the continuity of $\\Gamma_n$ at the point $w^*$, with an astronomically small tolerance. The exact “lift” of the last coordinate ensures that the whole tail is\nreproduced without error.\n```\n\nLet us check this numerically in $\\mathbb R^3$: we aim at $(1.5, -4, 7)$ with $\\delta=0.05$."
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19201141",
   "metadata": {},
   "outputs": [],
   "source": [
    "cel, delta = (1.5, -4, 7), 0.05\n",
    "w_gwiazdka, _ = podnies(cel[1], cel[2], delta)      # ogon: |h(w*) - a2| < δ, g(w*) = a3\n",
    "w, _ = podnies(cel[0], w_gwiazdka, delta)            # |h(w) - a1| < δ, g(w) = w*\n",
    "Gamma3 = (h(w), h(g(w)), g(g(w)))\n",
    "print(\"w =\", mp.nstr(w, 15))\n",
    "for j, (c, a) in enumerate(zip(Gamma3, cel), 1):\n",
    "    print(f\"współrzędna {j}: {mp.nstr(c, 12):>16}   błąd = {mp.nstr(abs(c - a), 3)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6af6f135",
   "metadata": {},
   "source": [
    "The first two coordinates differ from the target by $0.008$ and $0.010$, i.e., by less than $\\delta=0.05$,\n",
    "and the third equals $7$ to within the working precision, as Theorem 4.4 predicts.\n",
    "\n",
    "```{admonition} Remark 4.6 (density, not surjectivity)\n",
    ":class: note\n",
    "The image of $\\Gamma_n$ is dense, but it has **measure zero** in $\\mathbb R^n$ for $n\\ge2$: on a compact\n",
    "parameter interval of length $\\ell$ the curve is Lipschitz with some constant $L$, so its\n",
    "image can be covered by $N$ cubes of side $2L\\ell/N$, of total volume $(2L\\ell)^nN^{1-n}\\to0$; the whole parameter line is a countable union of such intervals.\n",
    "That is why hitting all coordinates exactly is the wrong goal — and it is not needed:\n",
    "it suffices to enter a neighborhood of the point (Fact 4.6 in {doc}`r1_pojecia`).\n",
    "```\n",
    "\n",
    "Let us plot an initial portion of the curve $\\Gamma_2$, for $t\\in[0,22]$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21481ee7",
   "metadata": {},
   "outputs": [],
   "source": [
    "t = np.linspace(0, 22, 400_000)\n",
    "fig, ax = plt.subplots(figsize=(5.2, 5.2))\n",
    "ax.plot(t*np.sin(t), t*np.sin(t**3), lw=0.15, color='#4f46e5')\n",
    "ax.set_xlim(-22, 22); ax.set_ylim(-22, 22); ax.set_aspect('equal')\n",
    "ax.set_title('Γ₂(t) = (t sin t, t sin t³), t ∈ [0, 22]')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ad30bde",
   "metadata": {},
   "source": [
    "In the plot, the curve merges into a solid patch: for $t\\le22$ the phase $t^3$ makes about $1700$\n",
    "turns, so successive sweeps of the second coordinate lie very close to one another. This is an artifact of the line width,\n",
    "since the image of the curve itself has measure zero (Remark 4.6)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "724ad5fb",
   "metadata": {},
   "source": "## 5. Transfer to one variable\n\n```{admonition} Lemma 5.1 (what substituting a dense curve preserves)\n:class: important\nLet $H\\colon\\mathbb R^n\\to\\mathbb R$ be continuous, $c\\in\\mathbb R$, $M\\ge0$. Then\n\n$$\n\\exists\\,\\mathbf u\\in\\mathbb R^n\\ \\ H(\\mathbf u)<c\\quad\\iff\\quad\\exists\\,t>M\\ \\ H(\\Gamma_n(t))<c ,\n$$\n\nand also $\\inf_{t>M}H(\\Gamma_n(t))=\\inf_{\\mathbf u\\in\\mathbb R^n}H(\\mathbf u)$.\n```\n\n**Proof.** “⇐”: take $\\mathbf u=\\Gamma_n(t)$. “⇒”: if $H(\\mathbf u_0)<c$, then by continuity\n$H<c$ on a cube $\\lVert\\mathbf u-\\mathbf u_0\\rVert_\\infty<\\eta$, and by Theorem 4.4 the curve\n$\\Gamma_n((M,\\infty))$ enters it. Equality of the infima: the curve lies in $\\mathbb R^n$, so\nthe $\\inf$ over the curve $\\ge\\inf$ over $\\mathbb R^n$; and for every $c>\\inf_{\\mathbb R^n}H$ the first\npart gives a point of the curve with $H<c$. $\\blacksquare$\n\nFor a **non-strict** inequality the analogous equivalence for an arbitrary dense set is false: $D=\\mathbb R\\setminus\\{0\\}$ is dense\nin $\\mathbb R$, and $H(z)=z^2$ has the same infimum $0$ on $D$ and on $\\mathbb R$, and yet\n$H(z)\\le0$ has a solution only in $\\mathbb R$. That is why we built the gap first (§3).\n\n```{admonition} Definition 5.2\n:class: note\n$G(y,t)=F\\bigl(y,\\Gamma_n(t)\\bigr)$ (substitution of $n$ expressions for $n$ variables) and\n$G_a(t)=G(a,t)$ for $a\\in\\mathbb N$. Thus $G\\in\\mathcal A_2$, $G_a\\in\\mathcal A_1$,\nand $G_a$ is obtained from $a$ algorithmically (by substituting the number $a$ for $y$).\n```\n\n```{admonition} Theorem 5.3 (dichotomy in one variable; Richardson, Corollary to Theorem Two)\n:class: important\nEvery function $G_a$ is nonnegative. Moreover:\n1. if $a\\in U$, then for every $\\varepsilon>0$ and $M\\ge0$ there is $t>M$ with $G_a(t)<\\varepsilon$;\n2. if $a\\notin U$, then $G_a(t)>1$ for every $t\\in\\mathbb R$.\n\nIn particular, $a\\in U\\iff\\exists t\\ G_a(t)<1\\iff\\exists t\\ G_a(t)\\le1\\iff\\inf_tG_a(t)=0$.\n```\n\n**Proof.** Nonnegativity: $F\\ge0$. If $a\\in U$, Corollary 3.7 gives $\\mathbf u_0$ with\n$F(a,\\mathbf u_0)=0$; Lemma 5.1 for $H=F(a,\\cdot)$ and $c=\\varepsilon$ gives the claim. If\n$a\\notin U$, then $F(a,\\mathbf u)>1$ at **every** point, in particular at the points $\\Gamma_n(t)$.\n$\\blacksquare$\n\n```{admonition} Remark 5.4 (why we do not claim that $G_a$ has a zero)\n:class: warning\nA zero of the function $F(a,\\cdot)$ yields arbitrarily small values of $G_a$ (density + continuity), but not\na zero of $G_a$ — the curve may miss that point. The arithmetic information is carried by the sharp threshold $1$,\nprotected by the rounding theorem. The order of the construction matters: first\nthe gap (§3), then the curve (§4). In the direction “$G_a(t)\\le1\\Rightarrow a\\in U$” we use\nnot density but only the gap: the point $\\Gamma_n(t)$ is itself a witness of $F\\le1$.\n```\n\n### The whole chain on a toy example\n\nThe actual polynomial from Theorem 1.1 is huge. We can, however, trace **the same\nconstruction** on a “Diophantine equation” in two variables: $x_1^2+x_2^2=5$ (which has the solution\n$(1,2)$) and $x_1^2+x_2^2=3$ (which has none). We build the weights, the penalty $f$, $F$ and\n$G(t)=F(\\Gamma_2(t))$, and then — in the “yes” case — we look for a point with $G(t)<1$ by aiming\nthe curve at the zero of $F$, i.e., at $\\mathbf u=(1,\\sqrt2)$ (since $f$ vanishes at $\\mathbf x=(1,2)=(u_1^2,u_2^2)$)."
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c755fe7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "mp.mp.dps = 120\n",
    "x1, x2, u1, u2 = sp.symbols('x1 x2 u1 u2')\n",
    "\n",
    "def lancuch(P, n=2):\n",
    "    \"\"\"Wagi k_i, kara f i funkcja F(u) = f(u1², u2²) — dokładnie według §2–§3.\"\"\"\n",
    "    Q = P**2\n",
    "    k = [majoranta(sp.diff(Q, xi)) for xi in (x1, x2)]\n",
    "    f = (n + 1)**4 * (P**2 + sum(sp.sin(sp.pi*xi)**2 * ki**4 for xi, ki in zip((x1, x2), k)))\n",
    "    F = f.subs({x1: u1**2, x2: u2**2}, simultaneous=True)\n",
    "    return k, sp.lambdify((u1, u2), F, 'mpmath')\n",
    "\n",
    "for opis, P, cel in [(\"x1²+x2²=5 (TAK)\", x1**2 + x2**2 - 5, (mp.mpf(1), mp.sqrt(2))),\n",
    "                     (\"x1²+x2²=3 (NIE)\", x1**2 + x2**2 - 3, (mp.mpf(1), mp.mpf(1)))]:\n",
    "    k, F = lancuch(P)\n",
    "    print(opis, \"   waga k1 =\", sp.factor(k[0]))\n",
    "    for delta in ('1e-3', '1e-8', '1e-10'):\n",
    "        t, _ = podnies(cel[0], cel[1], mp.mpf(delta))\n",
    "        print(f\"   δ = {delta:>6}:  t ≈ {mp.nstr(t, 12):>16}   G(t) = {mp.nstr(F(h(t), g(t)), 8)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19e894f6",
   "metadata": {},
   "source": "For the solvable equation a point with $G(t)<1$ exists, but our construction finds one only\nat $t\\approx1.26\\cdot10^{11}$, and it has to be computed with more than a hundred digits of precision (the phase is\n$t^3\\approx2\\cdot10^{33}$). For the\nunsolvable equation, even the “best attempt” gives $G\\approx81>1$ — in accordance with the theorem,\nwhich guarantees $G>1$ **everywhere**. The reduction is effective as a transformation of expressions,\nbut the witnesses can be astronomically far away: yet another reason why numerical\n“checking” cannot replace deciding.\n\n```{seealso}\nA larger example — the family of expressions from the equation $x^3+y^3+z^3=a$, including a case in which\nthe witness has about 2770 digits and a case in which nobody knows the answer — is in {doc}`r2_przyklad`.\n```\n\n## 6. The sign problem\n\n```{admonition} Theorem 6.1 (Theorem R, part A; Richardson, §2 Theorem One)\n:class: important\nThere is no algorithm that, given $A\\in\\mathcal A_1$, decides whether $\\exists t\\ A(t)<0$.\n```\n\n**Proof.** For $a\\in\\mathbb N$ we algorithmically build $A_a(t)=G_a(t)-1$. By Theorem 5.3,\n$a\\in U\\iff\\exists t\\ A_a(t)<0$. An algorithm for the sign problem would decide $U$, contrary to\nTheorem 1.1. $\\blacksquare$\n\nThe hard instances contain no absolute value: every $A_a$ is analytic and defined everywhere.\nBy Theorem 5.3, the reduction also works when the witness is sought only among $t>0$ or $t>M$.\nReplacing $A$ by $-A$ gives the undecidability of the question “is $A$ positive somewhere?”, and swapping\nthe answers, that of the question “is $A\\ge0$ everywhere?”.\n\n## 7. The identity (zero) problem\n\nThe absolute value turns a question about the **sign** into a question about **identity**:\n\n$$\n|s|-s=\\begin{cases}0,& s\\ge0,\\\\ -2s>0,& s<0.\\end{cases}\n$$\n\n```{admonition} Theorem 7.1 (Theorem R, part B; Richardson, §2 Theorem Two)\n:class: important\nThere is no algorithm that, given $B\\in\\mathcal B_1$, decides whether $B\\equiv0$.\n```\n\n**Proof.** Let $B_a(t)=|G_a(t)-1|-\\bigl(G_a(t)-1\\bigr)=|A_a(t)|-A_a(t)$. If $a\\notin U$,\nthen $G_a>1$ everywhere, so $B_a\\equiv0$. If $a\\in U$, then $G_a(t_0)<1$ at some $t_0$, so\n$B_a(t_0)=2(1-G_a(t_0))>0$. Hence $B_a\\equiv0\\iff a\\notin U$; an algorithm for the identity problem\n(with the answer swapped) would decide $U$. $\\blacksquare$\n\n```{admonition} Corollary 7.2 (equality and canonical forms)\n:class: important\nEquality of the functions defined by two expressions in $\\mathcal B_1$ is undecidable.\nIn particular, there is **no** algorithm assigning to every expression in $\\mathcal B_1$\na finite canonical form (such that the forms are equal if and only if the functions are\nequal).\n```\n\n**Proof.** $B\\equiv C\\iff B-C\\equiv0$. A canonical-form algorithm would decide equality\nby comparing two strings. $\\blacksquare$\n\nThis is the precise content of the conclusion in Lecture 1 that every `simplify` function must fail on\nsome expressions: it fails to recognize zero, gives a wrong answer, or does not terminate\n(see {doc}`../wyklady/w01_3_jak_dziala_cas`).\n\n```{admonition} Remark 7.3 (the role of the absolute value)\n:class: note\nThe absolute value is the bridge from sign to identity. For the purely analytic language $\\mathcal A_1$\nthis proof does **not** give undecidability of identity: an analytic function vanishing on an\ninterval vanishes everywhere (Theorem 4.2 in {doc}`r1_pojecia`), so a “plateau of zeros” like\n$|s|-s$ is impossible. Unlike analytic functions, functions with absolute value have zero divisors:\n$(|x|+x)(|x|-x)\\equiv0$, although neither factor is identically zero.\n```\n\n## 8. The integration problem\n\nWe ask whether, for a given $J\\in\\mathcal B_1$, there exists an **expression** $H\\in\\mathcal B_1$,\ndifferentiable on $\\mathbb R$, with $H'=J$ — a question about a *representable* antiderivative, not\nabout the existence of an antiderivative at all (for continuous $J$, one always exists: $\\int_0^xJ$).\n\n```{admonition} Definition 8.1 (local obstruction to integration)\n:class: note\nA function $\\Delta$ defined on $\\mathbb R$ and represented in a language $\\mathcal E$ is\na **local obstruction** if there exist no $H\\in\\mathcal E$ and no nonempty open interval\n$I$ on which $H$ is differentiable and $H'=\\Delta$.\n```\n\nIn {doc}`r3_dodatki` (Appendix B) we prove that $\\Delta(x)=e^{x^2}$ is a local obstruction\nfor $\\mathcal B_1$ (Liouville's theorem plus local removal of absolute values).\n\nWe need an expression that in the “no” case is identically zero, and in the “yes” case\nequals **exactly $1$ on some interval**. Richardson builds it from truncated subtraction:\n\n$$\nr\\mathbin{\\dot-}s=\\frac{|r-s|+(r-s)}{2}=\\max\\{r-s,0\\},\\qquad m(r,s)=r-(r\\mathbin{\\dot-}s)=\\min\\{r,s\\},\n$$\n\n$$\nS_a(t)=m\\bigl(1,\\ 2\\mathbin{\\dot-}2G_a(t)\\bigr)=\\min\\bigl\\{1,\\max\\{0,\\,2-2G_a(t)\\}\\bigr\\}\n=\\begin{cases}1,& G_a(t)\\le\\tfrac12,\\\\ 2-2G_a(t),& \\tfrac12\\le G_a(t)\\le1,\\\\ 0,& G_a(t)\\ge1.\\end{cases}\n$$\n\n$S_a\\in\\mathcal B_1$ is continuous and takes values in $[0,1]$.\n\n```{admonition} Lemma 8.2 (the switch)\n:class: important\nIf $a\\notin U$, then $S_a\\equiv0$. If $a\\in U$, then $S_a=1$ on some nonempty open interval.\n```\n\n**Proof.** In the first case $G_a>1$ everywhere. In the second, Theorem 5.3 gives $t_0$ with\n$G_a(t_0)<\\frac12$ (here we need the full strength of “$\\inf G_a=0$”, not just “$G_a<1$ somewhere”),\nand by continuity $G_a<\\frac12$ on a neighborhood of $t_0$. $\\blacksquare$\n\n```{admonition} Theorem 8.3 (Theorem R, part C; Richardson, §2 Theorem Three)\n:class: important\nLet a language $\\mathcal E$ of everywhere-defined functions effectively contain $\\mathcal B_1$, be\neffectively closed under multiplication, and contain a local obstruction $\\Delta$. Then there is no\nalgorithm deciding whether a given $J\\in\\mathcal E$ has an antiderivative in $\\mathcal E$.\nIn particular, this applies to $\\mathcal B_1$ with $\\Delta=e^{x^2}$.\n```\n\n**Proof.** Let $J_a=\\Delta\\cdot S_a$. If $a\\notin U$, then $J_a\\equiv0$, and the constant function $0$\nis an antiderivative of it in $\\mathcal E$. If $a\\in U$, then on some interval $I$ we have\n$S_a=1$, i.e., $J_a=\\Delta$; an antiderivative $H\\in\\mathcal E$ of $J_a$ would satisfy $H'=\\Delta$\non $I$, contrary to the definition of an obstruction. Hence $J_a$ has an antiderivative in $\\mathcal E$\nif and only if $a\\notin U$. $\\blacksquare$\n\n```{admonition} Remark 8.4 (the problem is global)\n:class: note\nFor $a\\in U$ the function $J_a$ may vanish on some other interval — there the antiderivative $0$ is\nelementary. The obstruction lies on the interval where $S_a=1$. We ask for **one** expression\nthat works on the whole line.\n```\n\n## 9. Richardson's original, general formulation\n\nRichardson works with an arbitrary set $E$ of expressions representing **partial** functions,\nand with the set of functions $E^*$. He assumes that $E^*$ contains the identity and the rational constants,\nand that for $A,B\\in E$ one can **algorithmically** build expressions for $A\\pm B$, $A\\cdot B$, $A(B(x))$.\nHe understands the equality $f\\equiv g$ with domains taken into account (Definition 3.3 in {doc}`r1_pojecia`). The conditions:\n\n* **(R1)** $E^*$ contains the constants $\\pi$, $\\log2$ and the functions $e^x$, $\\sin x$;\n* **(R2)** there is $\\mu\\in E^*$ with $\\mu(x)=|x|$ for $x\\neq0$ (the value $\\mu(0)$ is arbitrary or undefined);\n* **(R3)** there is an everywhere-defined $\\Delta\\in E^*$ such that for no $f\\in E^*$ and no\n  interval $I$ does $f'\\equiv\\Delta$ hold on $I$.\n\n```{admonition} Theorem 9.1 (Richardson, 1968)\n:class: important\nUnder the above effectiveness assumptions:\n1. (R1) ⇒ the question whether an expression takes a negative value at some point of its domain is undecidable;\n2. (R1)+(R2) ⇒ the identity problem $A\\equiv0$ is undecidable;\n3. (R1)+(R2)+(R3) ⇒ the integration problem $\\exists f\\in E^*\\ f'\\equiv A$ is undecidable.\n```\n\n**Proof.** The expressions $G_a$ from §5 have representatives in $E$: we fix, once and for all, expressions\nfor the finitely many constants and basic functions used in the construction ($x$, $e^x$, $\\sin x$), and apply the effective\nconstructors along the tree; the number $a$ is built from $1$ by addition. This gives (1) via $G_a-1$.\n\n(2): let $\\widetilde B_a=\\mu(G_a-1)-(G_a-1)$. If $a\\notin U$, the argument of $\\mu$ is never\nzero, so $\\widetilde B_a$ is defined everywhere and equal to $0$. If $a\\in U$, then at the point\n$t_0$ with $G_a(t_0)<1$ the argument is nonzero and $\\widetilde B_a(t_0)=2(1-G_a(t_0))>0$; hence\n$\\widetilde B_a\\not\\equiv0$ regardless of the behavior at other points.\n\n(3): in the cutoff we replace the absolute value by $\\mu$:\n$q_a=2-2G_a$, $T_a=\\frac{\\mu(q_a)+q_a}{2}$, $\\widetilde S_a=1-\\frac{\\mu(1-T_a)+(1-T_a)}{2}$.\nIf $a\\notin U$: $q_a<0$, so $T_a=0$ everywhere, and the outer $\\mu$ receives $1$, so\n$\\widetilde S_a$ is the everywhere-defined zero function. If $a\\in U$: on the interval where $G_a<\\frac12$ we have\n$q_a>1$, $T_a=q_a$, $1-T_a<0$, all arguments of $\\mu$ are nonzero, and $\\widetilde S_a=1$.\nThe rest is as in Theorem 8.3, with $\\widetilde J_a=\\Delta\\,\\widetilde S_a$ (the fact that $\\Delta$ is defined\neverywhere guarantees that in the “no” case $\\widetilde J_a$ is the everywhere-defined zero function). $\\blacksquare$\n\nAt the thresholds $G_a=1$ and $G_a=\\frac12$ the expressions involving $\\mu$ may be undefined — the proof avoids them:\nin the “no” case $G_a>1$ everywhere, and in the “yes” case we use an interval where $G_a<\\frac12$.\n\n## 10. What exactly we have proved\n\n**An effectiveness audit.** The reduction algorithm performs only operations on expressions:\nit takes the fixed $P$, forms $Q=P^2$, differentiates, builds the weights by the rules of Lemma 2.1, assembles $f$,\nsubstitutes the squares, then the coordinates of the curve, and finally the number $a$ for $y$. It never searches for\nroots, points of the curve, minima or signs of constants. These objects occur only\nin the **proof** that the constructed expression has the required property.\n\n```{admonition} Proposition 10.1 (negativity is semi-decidable)\n:class: important\nThere is an algorithm that, given $A\\in\\mathcal B_1$, halts if and only if\n$A(t)<0$ for some $t$.\n```\n\n**Proof.** The values of the constants, $\\exp$, $\\sin$ and $|\\cdot|$ at rational points can be\napproximated with a guaranteed error, and finite composition preserves this property. We enumerate\nthe pairs $(q,k)\\in\\mathbb Q\\times\\mathbb N$ and for each compute a rational $r_{q,k}$ with\n$|r_{q,k}-A(q)|\\le2^{-k}$; we halt when $r_{q,k}+2^{-k}<0$. The test never errs.\nIf $A(t_0)<0$, then by continuity $A<0$ on a neighborhood of $t_0$, hence at some rational $q$; for\nlarge $k$ the test succeeds. $\\blacksquare$\n\nThe same method semi-decides **not being identically zero**. By Post's theorem (Theorem 1.5\nin {doc}`r1_pojecia`) and Theorem 7.1, **being identically zero is not even semi-decidable** —\notherwise, combining the two procedures, we could decide it. Here is a working\nsemi-decision procedure using interval arithmetic:"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b790f708",
   "metadata": {},
   "outputs": [],
   "source": [
    "from fractions import Fraction\n",
    "from mpmath import iv\n",
    "iv.dps = 30\n",
    "\n",
    "def szukaj_ujemnej_wartosci(A, maks_krokow=10_000):\n",
    "    \"\"\"Półrozstrzyganie: przegląda wymierne q (coraz gęściej, coraz dalej) i zwraca q\n",
    "    z certyfikatem A(q) < 0 (górny kraniec przedziału ujemny) albo None po limicie kroków.\"\"\"\n",
    "    krok = 0\n",
    "    for poziom in range(1, 60):                    # siatka o kroku 2^-poziom na [-poziom, poziom]\n",
    "        mianownik = 2**poziom\n",
    "        for licznik in range(-poziom * mianownik, poziom * mianownik + 1):\n",
    "            krok += 1\n",
    "            if krok > maks_krokow:\n",
    "                return None\n",
    "            q = Fraction(licznik, mianownik)\n",
    "            wartosc = A(iv.mpf(q.numerator) / q.denominator)\n",
    "            if wartosc.b < 0:                      # cały przedział < 0: certyfikat\n",
    "                return q, wartosc\n",
    "\n",
    "print(szukaj_ujemnej_wartosci(lambda t: t**2 - 2*t + iv.mpf('0.99')))   # minimum −0,01 w t = 1\n",
    "print(szukaj_ujemnej_wartosci(lambda t: t**2 - 2*t + 1))                 # (t − 1)² ≥ 0: brak certyfikatu"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98229b6f",
   "metadata": {},
   "source": "In the first example the procedure found a certificate at $q=1$: the whole interval of values lies\nbelow zero. In the second, the result `None` means only that the step limit was exhausted, not the answer “no”:\nwithout the limit, the procedure would search for a certificate forever. Richardson's theorem says that no\nsuch procedure can be supplemented with an opposite procedure that halts exactly when\n$A\\ge0$ everywhere (cf. Problem 8 in {doc}`r5_zadania`).\n\n**Three different questions about zero.**\n\n| Question | Logical form | What we know |\n|---|---|---|\n| identically zero | $\\forall t\\ A(t)=0$ | undecidable in $\\mathcal B_1$ (Theorem 7.1) |\n| existence of a zero | $\\exists t\\ A(t)=0$ | undecidable (Wang 1974; Laczkovich 2003) — does not follow from the density of the curve alone |\n| whether a constant is zero | $c=0$, no variable | **open problem**; decidable for exponential-logarithmic constants assuming Schanuel's conjecture (Richardson 1997) |\n\nRichardson wrote in 1968 (p. 515): “No method is known for deciding whether a subelementary expression\nwith no variables in it represents a number less than zero. Whether or not such a method exists\nis an open question.” More in {doc}`r4_kontekst`.\n\n## 11. The modern version: polynomials and sine suffice\n\nMatiyasevich's theorem (Theorem 2.4 in {doc}`r1_pojecia`) allows us to take as $P$ an ordinary\npolynomial $p(y,\\mathbf x)\\in\\mathbb Z[y,\\mathbf x]$ with an undecidable set $U$. Then\nthe derivatives of $Q=p^2$ are polynomials, and the weights can be taken polynomial: if\n$\\partial Q/\\partial x_i=\\sum_\\alpha c_{i,\\alpha}\\,y^{\\alpha_0}x_1^{\\alpha_1}\\cdots x_n^{\\alpha_n}$, then\n\n$$\nk_i(y,\\mathbf x)=2+\\sum_\\alpha|c_{i,\\alpha}|\\,(y^2+2)^{\\alpha_0}\\prod_{j=1}^n(x_j^2+2)^{\\alpha_j}\n$$\n\nsatisfies (2.1) (the coefficients are known integers, so we compute $|c_{i,\\alpha}|$\nright away — this is not the absolute-value operation of the language). The penalty, the squares and the curve $h,g$ use only\narithmetic operations and the sine.\n\n```{admonition} Corollary 11.1 (Caviness 1970, after Matiyasevich)\n:class: important\nLet $\\mathcal S_1$ be the language generated by the rational numbers, $\\pi$, the variable $x$,\nthe operations $+,-,\\cdot$ and the function $\\sin$. The sign problem is undecidable for $\\mathcal S_1$;\nafter adding the absolute value, the identity problem is undecidable too.\n```\n\n**Proof.** We repeat §3–§5 with the polynomial $P$ and the above weights, and then §6–§7\nwithout change. $\\blacksquare$\n\nLaczkovich (2003) also removed $\\pi$: in the ring generated by the integers and\nthe functions $x$, $\\sin x^n$, $\\sin(x\\sin x^n)$ ($n=1,2,\\dots$) it is undecidable whether a function\ntakes a positive value and whether it has a root. See {doc}`r4_kontekst`."
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
