The Selective EyeSubscribe on Substack

The Riemann Hypothesis and AI

Prompted by: scientificamerican.com

21 November 202611 min read

Well I’m not reading 250,000 pages or running through the 17 million lines of the Lean library.

What I did do is write a test harness to apply the new math against five ‘real’ world tests that RH applies to.

T1 - Montgomery’s paid correlation which needs RH

The first 5,598 zeta zeros got checked and they match the random-matrix “GUE” pattern. The alternative solutions fit about 2 to 10 times worse.

T2 - Quantum Chaos

Simulated quantum kicked top, a spinning quantum system kicked at regular intervals. With time-reversal symmetry broken, the energy-level spacings match the zeta zeros’ patterns. The two control set-ups (regular motion, and chaos with time-reversal symmetry) each land in their own predicted pattern.

T3 - Schoenfeld’s bounds on how far prime counts stray

I looked at the first 5.76 million primes up to 100 million. Never above 98% of the allowed error; the explicit formula rebuilds the prime staircase from the zeros.

T4 - Robin’s inequality. It should be true exactly when RH is true.

When looking at n up to 10 million,the closest approach is 98.6% at n= 10,080. It found the 27 known small exceptions and nothing else.

T5 - Bach’s deterministic primality test which needs GRH.

Taking every number up to 200,000,3000 random 64-bit numbers and notorious “liar” composites, I got zero errors.

So, I suggest some physicists go test this in the real world as this was all run using python.

SO WHAT

For most of us, yeah, nothing much will change. What it impacts is how we approach solving complex problems and proving the solution is true.

It will make software you rely on marginally more secure. It will make for faster science because once machines can model problems, solve them, and verify the proof, the bottleneck in mathematics and part of physics shifts from checking to understanding. That will mean faster progress in optimising and modelling, which feeds into logistics, drug discovery, climate models, designing fusion reactor magnetic containment and so on.

It also creates a new standard for claims. A machine-verified proof gives a new benchmark for what “checked” actually means. In ten years, the same idea in other fields is going to impact statistics, any claim linked to sources a machine has actually checked, models whose assumptions are written out explicitly.

So when a Government makes a plausible argument about why they should do something we will all be able to say “did you check it?” and if they did, we can ask for the proof.

NOTES

Here’s the code and the results:

"""
Riemann Hypothesis "real-space" test suite
==========================================

Five results that depend on RH / GRH, each turned into a numerical test,
plus a simulated physical system (a quantum kicked top) that is checked
against the same statistics as the zeta zeros.

None of these can PROVE RH -- a finite check never can. What they do is
"coverage": each consequence of RH is exercised in a different region of
mathematics/physics, and a failure anywhere would be a counterexample.

  T1  Montgomery pair correlation (theorem, conditional on RH)
      zeta zeros vs GUE random-matrix prediction (quantum chaos)
  T2  Physical analogue: quantum kicked top, time-reversal broken
      -> should show the SAME level statistics as the zeta zeros (GUE),
      with controls: integrable top (Poisson), time-reversal top (GOE)
  T3  Schoenfeld's explicit bounds (conditional on RH)
      |pi(x)-li(x)| < sqrt(x) ln x / 8pi        for x >= 2657
      |psi(x)-x|    < sqrt(x) ln^2 x / 8pi      for x >= 73.2
      + explicit-formula "spectral synthesis" of the primes from zeros
  T4  Robin's criterion (EQUIVALENT to RH)
      sigma(n) < e^gamma n ln ln n              for all n > 5040
  T5  Bach's theorem (conditional on GRH)
      n is prime iff it passes Miller's strong test for all a < 2 ln^2 n
      (the deterministic primality test used in real cryptography)

Run:  python3 rh_realspace_tests.py
Needs: numpy scipy mpmath sympy matplotlib
"""

import json
import math
import random
import time

import numpy as np
from scipy import special, stats, linalg, optimize

RESULTS = {}


# ---------------------------------------------------------------------------
# Zeta zeros: vectorised Riemann-Siegel Z(t), sign changes, Brent refinement
# ---------------------------------------------------------------------------
def theta(t):
    t = np.asarray(t, dtype=float)
    return (t / 2) * np.log(t / (2 * np.pi)) - t / 2 - np.pi / 8 \
        + 1 / (48 * t) + 7 / (5760 * t ** 3)


def Z(t):
    """Riemann-Siegel Z(t) with first correction term (error ~ t^-5/4)."""
    t = np.atleast_1d(np.asarray(t, dtype=float))
    a = np.sqrt(t / (2 * np.pi))
    N = np.floor(a).astype(int)
    p = a - N
    th = theta(t)
    out = np.zeros_like(t)
    for n in range(1, N.max() + 1):
        m = N >= n
        out[m] += np.cos(th[m] - t[m] * np.log(n)) / np.sqrt(n)
    out *= 2
    psi0 = np.cos(2 * np.pi * (p * p - p - 1 / 16)) / np.cos(2 * np.pi * p)
    out += ((-1.0) ** (N - 1)) * (2 * np.pi / t) ** 0.25 * psi0
    return out


def zeta_zeros(T, step=0.005):
    ts = np.arange(10.0, T, step)
    vals = Z(ts)
    idx = np.where(np.sign(vals[:-1]) != np.sign(vals[1:]))[0]
    zeros = [optimize.brentq(lambda x: Z(x)[0], ts[i], ts[i + 1], xtol=1e-10)
             for i in idx]
    # polish with mpmath's exact Z(t): the fast approximation is loose at low t
    import mpmath
    mpmath.mp.dps = 20
    zeros = [float(mpmath.findroot(mpmath.siegelz, z)) if z < 400 else z
             for z in zeros]
    return np.array(zeros)


def N_smooth(t):
    """Smooth zero-counting function: theta(t)/pi + 1."""
    return theta(t) / np.pi + 1


# ---------------------------------------------------------------------------
# Random-matrix reference curves
# ---------------------------------------------------------------------------
def R2_gue(u):
    u = np.asarray(u, float)
    return 1 - np.sinc(u) ** 2          # np.sinc(u) = sin(pi u)/(pi u)


def R2_goe(u):
    u = np.asarray(u, float)
    pu = np.pi * u
    s = np.sinc(u)
    Si = special.sici(pu)[0]
    return 1 - s ** 2 + (Si / np.pi - 0.5 * np.sign(u)) * \
        (np.cos(pu) / u - np.sin(pu) / (np.pi * u ** 2))


def P_gue(s):  # Wigner surmise, beta = 2
    return (32 / np.pi ** 2) * s ** 2 * np.exp(-4 * s ** 2 / np.pi)


def P_goe(s):  # beta = 1
    return (np.pi / 2) * s * np.exp(-np.pi * s ** 2 / 4)


def P_poi(s):
    return np.exp(-s)


def cdf_from_pdf(pdf):
    grid = np.linspace(0, 8, 8001)
    c = np.cumsum(pdf(grid)) * (grid[1] - grid[0])
    c /= c[-1]
    return lambda x: np.interp(x, grid, c)


CDF = {"GUE": cdf_from_pdf(P_gue), "GOE": cdf_from_pdf(P_goe),
       "Poisson": cdf_from_pdf(P_poi)}


def classify_spacings(s):
    """KS distance of spacing sample to each ensemble; smallest wins."""
    d = {k: float(stats.kstest(s, f).statistic) for k, f in CDF.items()}
    return min(d, key=d.get), d


def pair_correlation(x, umax=3.0, bins=60):
    x = np.sort(x)
    diffs = []
    for k in range(1, 12):
        d = x[k:] - x[:-k]
        diffs.append(d[d < umax])
    diffs = np.concatenate(diffs)
    h, edges = np.histogram(diffs, bins=bins, range=(0, umax))
    centres = 0.5 * (edges[1:] + edges[:-1])
    dens = h / (len(x) * (edges[1] - edges[0]))
    return centres, dens


# ---------------------------------------------------------------------------
# T1  Montgomery pair correlation on zeta zeros
# ---------------------------------------------------------------------------
def test_T1(T=6000):
    t0 = time.time()
    g = zeta_zeros(T)
    # sanity: count vs smooth formula (Backlund-type check that no zeros
    # were missed OFF the line in this window -- the Gram/Turing idea)
    expected = N_smooth(T)
    import mpmath
    check = [float(mpmath.zetazero(n).imag) for n in (1, 2, 100, 1000, 3000)]
    max_err = max(abs(g[n - 1] - c) for n, c in zip((1, 2, 100, 1000, 3000), check))

    x = N_smooth(g)                     # unfold to mean spacing 1
    s = np.diff(x)
    u, dens = pair_correlation(x)
    rms = {"GUE": float(np.sqrt(np.mean((dens - R2_gue(u)) ** 2))),
           "GOE": float(np.sqrt(np.mean((dens - R2_goe(u)) ** 2))),
           "Poisson": float(np.sqrt(np.mean((dens - 1.0) ** 2)))}
    best_r2 = min(rms, key=rms.get)
    best_s, ks = classify_spacings(s)
    RESULTS["T1"] = dict(
        name="Montgomery pair correlation (RH-conditional)",
        zeros_found=len(g), height=T,
        zeros_expected_smooth=float(expected),
        count_discrepancy=float(len(g) - expected),
        max_abs_error_vs_mpmath=float(max_err),
        pair_corr_rms=rms, pair_corr_best=best_r2,
        spacing_KS=ks, spacing_best=best_s,
        passed=(best_r2 == "GUE" and best_s == "GUE"
                and abs(len(g) - expected) < 3
                and max_err < 1e-3),  # 0.1% of mean spacing: irrelevant to statistics
        seconds=round(time.time() - t0, 1))
    return g, x, s, u, dens


# ---------------------------------------------------------------------------
# T2  Quantum kicked top (physical analogue)
# ---------------------------------------------------------------------------
def spin_ops(j):
    m = np.arange(j, -j - 1, -1)
    Jz = np.diag(m)
    jp = np.diag(np.sqrt(j * (j + 1) - m[1:] * (m[1:] + 1)), 1)
    Jx = (jp + jp.T) / 2
    Jy = (jp - jp.T) / (2j)
    return Jx, Jy, Jz


def floquet_phases(U):
    ph = np.sort(np.angle(linalg.eigvals(U)))
    s = np.diff(np.concatenate([ph, [ph[0] + 2 * np.pi]]))
    return s / s.mean()


def test_T2(j=400):
    t0 = time.time()
    Jx, Jy, Jz = spin_ops(j)
    D = 2 * j + 1
    E = lambda H: linalg.expm(-1j * H)

    # (a) time-reversal broken, chaotic  -> expect GUE (like zeta zeros)
    U_gue = E(10.0 * Jz @ Jz / D + 1.7 * Jz) @ E(8.0 * Jy @ Jy / D + 1.1 * Jy) \
        @ E(6.0 * Jx @ Jx / D + 0.9 * Jx)
    s_gue = floquet_phases(U_gue)

    # (b) integrable control: no nonlinear kick -> expect Poisson
    #     (pure rotation is degenerate, so use a twist that conserves Jz)
    U_int = E(1.3 * Jz @ Jz / D + 0.7 * Jz)
    s_int = floquet_phases(U_int)

    # (c) time-reversal symmetric chaotic top -> expect GOE
    #     U = exp(-i k Jz^2/D) exp(-i p Jy) has parity R=exp(-i pi Jy);
    #     diagonalise within one parity sector
    U_goe = E(6.0 * Jz @ Jz / D) @ E(1.7 * Jy)
    R = E(np.pi * Jy)
    w, V = linalg.eig(R)
    sector = V[:, np.isclose(w, w[np.argmax(w.real)], atol=1e-6)]
    Q, _ = np.linalg.qr(sector)
    s_goe = floquet_phases(Q.conj().T @ U_goe @ Q)

    out = {}
    for label, s, want in (("chaotic_T_broken", s_gue, "GUE"),
                           ("integrable", s_int, "Poisson"),
                           ("chaotic_T_symmetric", s_goe, "GOE")):
        best, ks = classify_spacings(s)
        out[label] = dict(levels=len(s), expected=want, best=best, KS=ks,
                          ok=best == want)
    RESULTS["T2"] = dict(name="Quantum kicked top physical analogue",
                         spin_j=j, cases=out,
                         passed=all(v["ok"] for v in out.values()),
                         seconds=round(time.time() - t0, 1))
    return s_gue, s_int, s_goe


# ---------------------------------------------------------------------------
# T3  Schoenfeld bounds + explicit formula
# ---------------------------------------------------------------------------
def primes_upto(n):
    sieve = np.ones(n + 1, dtype=bool)
    sieve[:2] = False
    for p in range(2, int(n ** 0.5) + 1):
        if sieve[p]:
            sieve[p * p::p] = False
    return np.nonzero(sieve)[0]


def li(x):
    return special.expi(np.log(x))


def test_T3(X=10 ** 8, zeros=None):
    t0 = time.time()
    P = primes_upto(X)
    # pi(x) - li(x) is extremal at primes (just before and at the jump)
    pf = P.astype(float)
    pi_at = np.arange(1, len(P) + 1, dtype=float)
    m = pf >= 2657
    L = li(pf[m])
    bound = np.sqrt(pf[m]) * np.log(pf[m]) / (8 * np.pi)
    # left limit x -> p^- only counts if it lies in x >= 2657 (i.e. p > 2657)
    left = np.where(pf[m] > 2657, np.abs(pi_at[m] - 1 - L), 0.0)
    dev = np.maximum(np.abs(pi_at[m] - L), left)
    pi_ratio = dev / bound

    # psi(x): prime powers with log p weights
    pk, w = [], []
    for p in P[P <= int(X ** 0.5)]:
        q = int(p) * int(p)
        while q <= X:
            pk.append(q); w.append(math.log(p)); q *= int(p)
    allpts = np.concatenate([pf, np.array(pk, float)])
    allw = np.concatenate([np.log(pf), np.array(w)])
    o = np.argsort(allpts)
    xs, psi = allpts[o], np.cumsum(allw[o])
    m2 = xs >= 74
    b2 = np.sqrt(xs[m2]) * np.log(xs[m2]) ** 2 / (8 * np.pi)
    d2 = np.maximum(np.abs(psi[m2] - xs[m2]),
                    np.abs(psi[m2] - allw[o][m2] - xs[m2]))
    psi_ratio = d2 / b2

    RESULTS["T3"] = dict(
        name="Schoenfeld explicit prime bounds (RH-conditional)",
        x_max=X, primes_checked=int(len(P)),
        pi_bound_max_ratio=float(pi_ratio.max()),
        pi_bound_worst_x=int(pf[m][np.argmax(pi_ratio)]),
        psi_bound_max_ratio=float(psi_ratio.max()),
        psi_bound_worst_x=int(xs[m2][np.argmax(psi_ratio)]),
        passed=bool(pi_ratio.max() < 1 and psi_ratio.max() < 1),
        seconds=round(time.time() - t0, 1))

    # explicit formula: psi_0(x) = x - sum_rho x^rho/rho - ln 2pi - .5 ln(1-x^-2)
    synth = None
    if zeros is not None:
        xg = np.linspace(2, 60, 3000)
        synth = {}
        for K in (10, 100, len(zeros)):
            g = zeros[:K]
            rho = 0.5 + 1j * g
            S = np.zeros_like(xg)
            for r in rho:
                S += 2 * np.real(np.exp(r * np.log(xg)) / r)
            synth[K] = xg - S - math.log(2 * math.pi) - 0.5 * np.log(1 - xg ** -2.0)
        idx = np.searchsorted(xs, xg, side="right") - 1
        true_psi = np.where(idx >= 0, psi[np.clip(idx, 0, None)], 0.0)
        synth["x"], synth["true"] = xg, true_psi
    return synth


# ---------------------------------------------------------------------------
# T4  Robin's criterion
# ---------------------------------------------------------------------------
def test_T4(N=10 ** 7):
    t0 = time.time()
    sigma = np.zeros(N + 1, dtype=np.int64)
    for d in range(1, N + 1):
        sigma[d::d] += d
    n = np.arange(5041, N + 1, dtype=float)
    ratio = sigma[5041:] / (np.exp(np.euler_gamma) * n * np.log(np.log(n)))
    k = int(np.argmax(ratio))
    small = np.arange(2, 5041, dtype=float)
    small_viol = int(np.sum(sigma[2:5041] >=
                            np.exp(np.euler_gamma) * small * np.log(np.log(small))))
    RESULTS["T4"] = dict(
        name="Robin's criterion (equivalent to RH)",
        n_max=N, max_ratio=float(ratio[k]), worst_n=int(5041 + k),
        violations_above_5040=int(np.sum(ratio >= 1)),
        known_small_exceptions_found=small_viol,   # known: exactly 27 (2..5040)
        passed=bool(ratio.max() < 1),
        seconds=round(time.time() - t0, 1))


# ---------------------------------------------------------------------------
# T5  Bach / GRH deterministic Miller test
# ---------------------------------------------------------------------------
def strong_probable_prime(n, a):
    d, s = n - 1, 0
    while d % 2 == 0:
        d //= 2; s += 1
    x = pow(a, d, n)
    if x == 1 or x == n - 1:
        return True
    for _ in range(s - 1):
        x = x * x % n
        if x == n - 1:
            return True
    return False


def miller_grh(n):
    if n < 2:
        return False
    for p in (2, 3, 5, 7):
        if n % p == 0:
            return n == p
    limit = min(n - 1, int(2 * math.log(n) ** 2))
    return all(strong_probable_prime(n, a) for a in range(2, limit + 1))


def test_T5(exhaustive=200_000, randoms=3000, seed=1):
    from sympy import isprime   # deterministic below 2^64
    t0 = time.time()
    P = set(primes_upto(exhaustive).tolist())
    mism = [n for n in range(2, exhaustive + 1) if miller_grh(n) != (n in P)]
    # notorious strong pseudoprimes (fool many fixed-base tests)
    hard = [2047, 1373653, 25326001, 3215031751, 2152302898747,
            3474749660383, 341550071728321, 3825123056546413051]
    carmichael = [561, 1105, 1729, 2465, 2821, 6601, 8911, 41041, 825265,
                  321197185, 5394826801, 232250619601, 9746347772161]
    rng = random.Random(seed)
    rand = [rng.getrandbits(64) | 1 for _ in range(randoms)]
    rand += [rng.choice([p for p in range(10**6, 10**6 + 2000) if isprime(p)]) *
             rng.choice([p for p in range(10**6, 10**6 + 2000) if isprime(p)])
             for _ in range(200)]
    extra = [n for n in hard + carmichael + rand if miller_grh(n) != isprime(n)]
    RESULTS["T5"] = dict(
        name="Bach's deterministic Miller test (GRH-conditional)",
        exhaustive_up_to=exhaustive, exhaustive_mismatches=len(mism),
        pseudoprimes_and_carmichaels=len(hard) + len(carmichael),
        random_64bit=randoms, semiprimes=200,
        other_mismatches=len(extra),
        passed=(not mism and not extra),
        seconds=round(time.time() - t0, 1))


# ---------------------------------------------------------------------------
def plot(g_data, top_data, synth, path="rh_realspace_results.png"):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    g, x, s, u, dens = g_data
    s_gue, s_int, s_goe = top_data
    fig, ax = plt.subplots(2, 2, figsize=(13, 9))
    uu = np.linspace(0.01, 3, 400)

    a = ax[0, 0]
    a.bar(u, dens, width=u[1] - u[0], color="#c9d6e8", label=f"zeta zeros (n={len(g)})")
    a.plot(uu, R2_gue(uu), "k", lw=2, label="GUE / Montgomery")
    a.plot(uu, R2_goe(uu), "--", color="#d07a2a", label="GOE")
    a.axhline(1, ls=":", color="grey", label="Poisson")
    a.set_title("T1  Pair correlation of zeta zeros")
    a.set_xlabel("unfolded separation u"); a.legend()

    a = ax[0, 1]
    ss = np.linspace(0, 4, 400)
    bins = np.linspace(0, 4, 41)
    a.hist(s, bins=bins, density=True, histtype="step", lw=2,
           color="#3a6fb0", label="zeta zeros")
    a.hist(s_gue, bins=bins, density=True, histtype="step", lw=2,
           color="#b0413e", label="kicked top, T broken")
    a.hist(s_goe, bins=bins, density=True, histtype="step", lw=1.2,
           color="#d07a2a", label="kicked top, T symmetric")
    a.hist(s_int, bins=bins, density=True, histtype="step", lw=1.2,
           color="grey", label="integrable top")
    a.plot(ss, P_gue(ss), "k", lw=1.5, label="GUE surmise")
    a.plot(ss, P_goe(ss), "k--", lw=1, label="GOE surmise")
    a.plot(ss, P_poi(ss), "k:", lw=1, label="Poisson")
    a.set_title("T1+T2  Nearest-neighbour spacings: primes vs physics")
    a.set_xlabel("spacing s"); a.legend(fontsize=8)

    a = ax[1, 0]
    if synth:
        a.plot(synth["x"], synth["true"], "k", lw=1.5, label="true ψ(x)")
        for K, c in ((10, "#d07a2a"), (100, "#3a6fb0")):
            a.plot(synth["x"], synth[K], color=c, lw=1, label=f"{K} zeros")
        Kmax = [k for k in synth if isinstance(k, int)][-1]
        a.plot(synth["x"], synth[Kmax], color="#b0413e", lw=1,
               label=f"{Kmax} zeros")
    a.set_title("T3  Rebuilding the primes from the zeros (explicit formula)")
    a.set_xlabel("x"); a.legend(fontsize=8)

    a = ax[1, 1]
    names = ["T1", "T2", "T3", "T4", "T5"]
    vals = [RESULTS[n]["passed"] for n in names]
    a.barh(names[::-1], [1] * 5, color=["#4c9a5a" if v else "#b0413e" for v in vals[::-1]])
    for i, n in enumerate(names[::-1]):
        a.text(0.02, i, RESULTS[n]["name"], va="center", color="white", fontsize=9)
    a.set_xticks([]); a.set_title("Suite summary (green = pass)")
    fig.tight_layout()
    fig.savefig(path, dpi=130)


if __name__ == "__main__":
    print("T1 zeta zeros + pair correlation ..."); g_data = test_T1()
    print("T2 kicked top ...");                    top = test_T2()
    print("T3 Schoenfeld bounds ...");             synth = test_T3(zeros=g_data[0])
    print("T4 Robin ...");                         test_T4()
    print("T5 Bach/GRH Miller ...");               test_T5()
    plot(g_data, top, synth)
    print(json.dumps(RESULTS, indent=2, default=lambda o: o.item() if hasattr(o, "item") else str(o)))
    with open("rh_realspace_results.json", "w") as f:
        json.dump(RESULTS, f, indent=2, default=lambda o: o.item() if hasattr(o, "item") else str(o))

Comments for this piece live on Substack.

Discuss on SubstackSubscribe