"""Bound how far the readings of z^2 of one tree by Hifuku's engines can differ.

Every engine reads one tree, with the same float32 branch lengths, against the
same three anchors, through the same formulas.  They differ in precision, which
each records as a kind: float32 (the CUDA device), float-float (the WGSL
device) and float64 (the host).  Each reading is bounded against the exact
value, so any two readings differ by at most the sum of their bounds.

The CUDA device (kind float32), for each anchor:
  - adds each run of merged edges in float32 (a run of r nonnegative lengths),
    and joins the two root-child runs of one split in float64;
  - reads the anchor's split lengths rounded from float64 to float32;
  - forms A = sum l^2, B = sum l l_ref and C = sum l_ref^2 in float64, where each
    product of two float32 values is exact;
  - forms cos = B / sqrt(A C), s^2 = (1 - w)(1 - min(1, cos)) + w t, clamped at 0.

The WGSL device (kind float-float) adds each run in float32 as the CUDA device
does, and joins the two root-child runs in float-float, which is exact for two
float32 values.  It reads the anchor's split lengths rounded to float32, forms
A and B in float-float, and takes C as the host's float64 value split into two
float32 parts.  It forms cos = B rsqrt(A) rsqrt(C) with the float-float
reciprocal square root.  An A below the domain of that root (2^-60) is first
multiplied by 2^80 and B by 2^40, exactly, which leaves the cosine unchanged;
an A below 2^-100 counts as a cosine of zero, and the bound below does not
cover it.  It forms s^2 = W (1 - min(1, cos)) + T rf in float-float,
with W = fl64(1 - w) and T = fl64(w / rf_max) split into two float32 parts and
rf an exact integer.

The host does the same as the CUDA device in float64, adds the run lengths in
float64, uses the anchor's float64 split lengths, and forms A, B and C with
Python's compensated sum.

The CUDA device and the host then map the three squared distances to z^2 with
one float64 closed form, with the first anchor at the origin, and the WGSL
device with the same closed form in float-float, its float64 constants split:

    X = M (o - (s2^2 - s1^2, s3^2 - s1^2)),   c = |X|^2 - s1^2,   z^2 = max(0, -c).

The WGSL device returns z = (-c) rsqrt(-c) as a float-float value, or 0 when
-c < 2^-60, and the host squares the float64 value of z.

This script confirms, with SymPy, each step of the bound in hifuku/precision.py:

1.  Lemma 3.3: gamma_j + gamma_k + gamma_j gamma_k <= gamma_{j+k}.
2.  A weighted mean of relative factors in [lo, hi] lies in [lo, hi], and a
    product of positive interval factors lies between the corner products.  So a
    sum of nonnegative terms that are each off by such a factor is off by one too.
3.  The computed cosine is the exact cosine times a factor F that increases with
    the rounding of B and decreases with the rounding of A, C and the three
    float64 operations.  Its extremes lie at the corners of the intervals, and
    to first order the device factor is 1 + 2 r u.  The float-float cosine
    B rsqrt(A) rsqrt(C) is the exact cosine times a factor monotone in each of
    its factors, also 1 + 2 r u to first order.
4.  The clamps min(1, .) and max(0, .) do not increase a difference.
5.  The difference of the two squared distances expands into terms that the
    rounding intervals bound, for the float-float engine with its split
    constants as for the others.
6.  The exact identity z^2(s + D) - z^2(s) = D1 - 2 X . DX - |DX|^2 with
    DX = -M (D2 - D1, D3 - D1), and |M v| <= ||M||_F |v|.  The barycentric
    coordinates lambda = M_bary (X - P3) move by M_bary DX, so by at most
    ||M_bary||_F |DX|.
7.  The per-operation identities of the running error bound for the closed form,
    with the split constants of the float-float closed form.
8.  A stored z gives z^2 back within gamma_3 in float64, and a float-float z
    within (1 + rho)^2 (1 + u_f)^2 (1 + v)^3, or 2^-60 when it is returned as
    0; a float-float coordinate returned in float64 adds one rounding.
9.  The assembled bound vanishes when the unit roundoffs do.

u and v are free symbols for the unit roundoffs of float32 and float64; u_f is
the float-float unit roundoff, the larger of the relative bounds of ff_add and
ff_mul, which satisfy the standard model (2.4) with it; rho is the relative
bound of the float-float reciprocal square root; and delta_s bounds the
relative error of a float64 value split into two float32 parts.  The run length
r and the term counts are free symbols.  No measured number enters.

Ref: higham2002accuracy (Theorem 2.2; model (2.4) and (2.5); Lemma 3.1;
Lemma 3.3; exact products, section 3.1; (3.5); (4.3), (4.4), (4.10); running
error analysis, section 3.3).
Ref: joldes2017tight and muller2022formalization (the float-float bounds);
w3c2026wgsl (section 15.7.4.1).
Ref: kuhner1994branch (branch score), robinson1981rf (Robinson-Foulds count).
Implements hifuku/precision.py.
"""
import sympy as sp


def check_zero(name, expr):
    simplified = sp.simplify(expr)
    assert simplified == 0, f"{name}: expected 0, got {simplified}"
    print(f"  PASS  {name}")


def check_nonnegative(name, expr):
    together = sp.factor(sp.together(sp.simplify(expr)))
    assert together.is_nonnegative, f"{name}: not shown nonnegative: {together}"
    print(f"  PASS  {name}")


def gamma(k, unit):
    """gamma_k = k u / (1 - k u), from Lemma 3.1."""
    return k * unit / (1 - k * unit)


u, v = sp.symbols("u v", positive=True)          # float32, float64 unit roundoff

# ---------------------------------------------------------------------------
print("1. Lemma 3.3: gamma_j + gamma_k + gamma_j gamma_k <= gamma_{j+k}")
# Write j u = p / (1 + p + q) and k u = q / (1 + p + q) with p, q > 0, which is
# every case with (j + k) u < 1.
p, q = sp.symbols("p q", positive=True)
ju, ku = p / (1 + p + q), q / (1 + p + q)


def g_of(x):
    return x / (1 - x)


check_nonnegative("gamma_{j+k} - (gamma_j + gamma_k + gamma_j gamma_k)",
                  g_of(ju + ku) - (g_of(ju) + g_of(ku) + g_of(ju) * g_of(ku)))

# ---------------------------------------------------------------------------
print("2. Weighted means and products of interval factors")
n_terms = 4
x = sp.symbols(f"x0:{n_terms}", positive=True)        # nonnegative summands
t = sp.symbols(f"t0:{n_terms}", positive=True)        # position in the interval
lo, spread = sp.symbols("lo spread", positive=True)
hi = lo + spread
factor = [lo + spread * t[i] / (1 + t[i]) for i in range(n_terms)]
mean = sum(x[i] * factor[i] for i in range(n_terms)) / sum(x)
check_nonnegative("weighted mean - lo >= 0", mean - lo)
check_nonnegative("hi - weighted mean >= 0", hi - mean)

xl, xs, yl, ys, tx, ty = sp.symbols("xl xs yl ys tx ty", positive=True)
xv = xl + xs * tx / (1 + tx)
yv = yl + ys * ty / (1 + ty)
check_nonnegative("x y - x_lo y_lo >= 0", xv * yv - xl * yl)
check_nonnegative("x_hi y_hi - x y >= 0", (xl + xs) * (yl + ys) - xv * yv)

# ---------------------------------------------------------------------------
print("3. The computed cosine is the exact cosine times a monotone factor")
A, B, C = sp.symbols("A B C", positive=True)          # exact parts
a, b, c = sp.symbols("a b c", positive=True)          # relative factors of A, B, C
e1, e2, e3 = sp.symbols("e1 e2 e3", positive=True)    # 1 + delta of *, sqrt, /
cos_exact = B / sp.sqrt(A * C)
# fl(A C) = A C (1 + d1); fl(sqrt(q)) = sqrt(q)(1 + d2); fl(B / r) = (B / r)(1 + d3)
cos_computed = (B * b) * e3 / (sp.sqrt((A * a) * (C * c) * e1) * e2)
F = b * e3 / (sp.sqrt(a * c * e1) * e2)
check_zero("computed cosine = exact cosine * F", cos_computed - cos_exact * F)
for name, sym, power in (("b", b, 1), ("a", a, sp.Rational(-1, 2)),
                         ("c", c, sp.Rational(-1, 2)),
                         ("e1", e1, sp.Rational(-1, 2)), ("e2", e2, -1),
                         ("e3", e3, 1)):
    # d F / d sym = power F / sym, so the sign of the derivative is the sign of
    # the power, and F is monotone in each factor.
    check_zero(f"dF/d{name} = ({power}) F / {name}",
               sp.diff(F, sym) - power * F / sym)

r, n_a, n_b, n_c = sp.symbols("r n_A n_B n_C", positive=True)
# Device intervals.  A float32 run sum of r nonnegative lengths is within
# gamma_{r-1}(u).  The two root-child runs of one split are added in float64, and
# a length formed that way is no longer a float32 value, so its square and its
# product with an anchor length each round once in float64.  With the float64
# sum of n nonnegative terms, Lemma 3.3 gathers these into gamma_{n+2}(v) for A
# and gamma_{n+1}(v) for B.  An anchor length rounded to float32 is within u
# (Theorem 2.2), and the square of a float32 value is exact in float64 (section
# 3.1), so C carries gamma_{n-1}(v) from its sum alone.
g_run32 = gamma(r - 1, u)
a_lo_dev = (1 - g_run32) ** 2 * (1 - gamma(n_a + 2, v))
b_hi_dev = (1 + g_run32) * (1 + u) * (1 + gamma(n_b + 1, v))
c_lo_dev = (1 - u) ** 2 * (1 - gamma(n_c - 1, v))
F_hi_dev = b_hi_dev * (1 + v) / (sp.sqrt(a_lo_dev * c_lo_dev * (1 - v)) * (1 - v))
first_order = sp.series(F_hi_dev.subs(v, 0) - 1, u, 0, 2).removeO()
check_zero("device cosine factor to first order is 1 + 2 r u",
           sp.simplify(first_order - 2 * r * u))

# The float-float form: cos = B rsqrt(A) rsqrt(C), with each reciprocal square
# root within a relative rho and each of the two products within u_f.
u_f, rho, delta_s = sp.symbols("u_f rho delta_s", positive=True)
g1, g2, h1, h2 = sp.symbols("g1 g2 h1 h2", positive=True)   # 1 + delta of rsqrt, rsqrt, *, *
cos_ff = (B * b) * (g1 / sp.sqrt(A * a)) * (g2 / sp.sqrt(C * c)) * h1 * h2
F_ff = b * g1 * g2 * h1 * h2 / sp.sqrt(a * c)
check_zero("float-float cosine = exact cosine * F_ff", cos_ff - cos_exact * F_ff)
for name, sym, power in (("b", b, 1), ("a", a, sp.Rational(-1, 2)),
                         ("c", c, sp.Rational(-1, 2)), ("g1", g1, 1), ("g2", g2, 1),
                         ("h1", h1, 1), ("h2", h2, 1)):
    check_zero(f"dF_ff/d{name} = ({power}) F_ff / {name}",
               sp.diff(F_ff, sym) - power * F_ff / sym)
# Float-float intervals.  The runs are float32 sums, as on the CUDA device; the
# join of the two root-child runs is exact.  A is a float-float sum of n_A
# products and B of n_B products of float32 values, each operation within u_f,
# so gamma_(n_A)(u_f) and gamma_(n_B)(u_f) by Lemma 3.1.  C is the host's float64
# value, gamma_(n_C - 1)(v) as on the CUDA device, split into float-float.
a_lo_ff = (1 - g_run32) ** 2 * (1 - gamma(n_a, u_f))
b_hi_ff = (1 + g_run32) * (1 + u) * (1 + gamma(n_b, u_f))
c_lo_ff = (1 - u) ** 2 * (1 - gamma(n_c - 1, v)) * (1 - delta_s)
F_hi_ff = b_hi_ff * (1 + rho) ** 2 * (1 + u_f) ** 2 / sp.sqrt(a_lo_ff * c_lo_ff)
first_order_ff = sp.series(F_hi_ff.subs({v: 0, u_f: 0, rho: 0, delta_s: 0}) - 1,
                           u, 0, 2).removeO()
check_zero("float-float cosine factor to first order is 1 + 2 r u",
           sp.simplify(first_order_ff - 2 * r * u))

# ---------------------------------------------------------------------------
print("4. The clamps do not increase a difference")
pp, qq = sp.symbols("pp qq", positive=True)
# min(1, .): one argument below 1 at 1 - pp, the other above at 1 + qq.
check_nonnegative("|min(1, 1-pp) - min(1, 1+qq)| <= |(1-pp) - (1+qq)|",
                  (pp + qq) - pp)
# max(0, .): one argument at -pp, the other at qq.
check_nonnegative("|max(0, -pp) - max(0, qq)| <= |-pp - qq|", (pp + qq) - qq)
# With both arguments on one side, each clamp is the identity or a constant.

# ---------------------------------------------------------------------------
print("5. The difference of the two squared distances")
W, T = sp.symbols("W T", positive=True)               # fl(1 - w), fl(w t): shared
L_dev, L_host = sp.symbols("L_dev L_host", real=True)
d5, d6, d5h, d6h = sp.symbols("d5 d6 d5h d6h", real=True)
s_dev = (W * L_dev * (1 + d5) + T) * (1 + d6)
s_host = (W * L_host * (1 + d5h) + T) * (1 + d6h)
check_zero("s_dev - s_host expansion",
           (s_dev - s_host)
           - (W * (L_dev * (1 + d5) * (1 + d6) - L_host * (1 + d5h) * (1 + d6h))
              + T * (d6 - d6h)))
X_, Y_, th, thp = sp.symbols("X Y theta theta_p", real=True)
check_zero("X(1 + theta) - Y(1 + theta') = (X - Y) + X theta - Y theta'",
           X_ * (1 + th) - Y_ * (1 + thp) - ((X_ - Y_) + X_ * th - Y_ * thp))
cd, ch, d4, d4h = sp.symbols("c_dev c_host d4 d4h", real=True)
check_zero("L_dev - L_host with L = (1 - c)(1 + d4)",
           (1 - cd) * (1 + d4) - (1 - ch) * (1 + d4h)
           - ((ch - cd) + (1 - cd) * d4 - (1 - ch) * d4h))
# One engine against the exact squared distance.  W = fl(1 - w) carries one
# rounding, T = fl(w fl(rf / rf_max)) carries two, and the product and the sum
# carry one each, so W L (1 + d5)(1 + d6) = (1 - w) L (1 + theta3) and
# T (1 + d6) = w t (1 + theta3'), each with three factors (Lemma 3.1).
wv, tv, Lc, ce, dw, dt1, dt2 = sp.symbols("w t L c dw dt1 dt2", real=True)
theta3 = (1 + dw) * (1 + d5) * (1 + d6) - 1
theta3p = (1 + dt1) * (1 + dt2) * (1 + d6) - 1
s_engine = ((1 - wv) * (1 + dw) * Lc * (1 + d5) + wv * tv * (1 + dt1) * (1 + dt2)) \
    * (1 + d6)
s_exact = (1 - wv) * (1 - ce) + wv * tv
check_zero("s_engine - s_exact = (1-w)(L - (1-c)) + (1-w) L theta3 + w t theta3'",
           s_engine - s_exact
           - ((1 - wv) * (Lc - (1 - ce)) + (1 - wv) * Lc * theta3
              + wv * tv * theta3p))
# The float-float engine: W = fl64(1 - w) split (dw, ds1), its product with L
# (d5) and the sum (d6) in float-float; T = fl64(w / rf_max) split (dt1, ds2)
# times the exact integer rf (d5p) in float-float.  Each term then carries
# theta_f <= (1 + v)(1 + delta_s)(1 + u_f)^2 - 1, the same identity with these
# factors.
ds1, ds2, d5p, rf_, rf_max_ = sp.symbols("ds1 ds2 d5p rf rf_max", real=True)
s_ff = ((1 - wv) * (1 + dw) * (1 + ds1) * Lc * (1 + d5)
        + wv / rf_max_ * (1 + dt1) * (1 + ds2) * rf_ * (1 + d5p)) * (1 + d6)
theta_f = (1 + dw) * (1 + ds1) * (1 + d5) * (1 + d6) - 1
theta_fp = (1 + dt1) * (1 + ds2) * (1 + d5p) * (1 + d6) - 1
check_zero("s_ff - s_exact has the same form, with t = rf / rf_max",
           (s_ff - s_exact.subs(tv, rf_ / rf_max_))
           - ((1 - wv) * (Lc - (1 - ce)) + (1 - wv) * Lc * theta_f
              + wv * rf_ / rf_max_ * theta_fp))

# ---------------------------------------------------------------------------
print("6. The perturbation identity for z^2, and the Frobenius bound")
m00, m01, m10, m11, o0, o1 = sp.symbols("m00 m01 m10 m11 o0 o1", real=True)
s1, s2, s3, D1, D2, D3 = sp.symbols("s1 s2 s3 D1 D2 D3", real=True)
M = sp.Matrix([[m00, m01], [m10, m11]])
o = sp.Matrix([o0, o1])


def X_of(t1, t2, t3):
    return M * (o - sp.Matrix([t2 - t1, t3 - t1]))


def z2_of(t1, t2, t3):
    X_vec = X_of(t1, t2, t3)
    return t1 - X_vec.dot(X_vec)


X0 = X_of(s1, s2, s3)
dX = X_of(s1 + D1, s2 + D2, s3 + D3) - X0
check_zero("DX = -M (D2 - D1, D3 - D1)",
           (dX + M * sp.Matrix([D2 - D1, D3 - D1])).norm())
check_zero("z2(s + D) - z2(s) = D1 - 2 X.DX - |DX|^2",
           z2_of(s1 + D1, s2 + D2, s3 + D3) - z2_of(s1, s2, s3)
           - (D1 - 2 * X0.dot(dX) - dX.dot(dX)))
v0, v1 = sp.symbols("v0 v1", real=True)
Mv = M * sp.Matrix([v0, v1])
check_zero("||M||_F^2 |v|^2 - |M v|^2 is a sum of squares",
           (m00**2 + m01**2 + m10**2 + m11**2) * (v0**2 + v1**2) - Mv.dot(Mv)
           - ((m00 * v1 - m01 * v0) ** 2 + (m10 * v1 - m11 * v0) ** 2))
# The barycentric coordinates lambda = M_bary (X - P3) are linear in X, so the
# same Frobenius bound gives |D lambda| <= ||M_bary||_F |DX|, and each
# coordinate moves by at most that.
b00, b01, b10, b11, p30, p31 = sp.symbols("b00 b01 b10 b11 p30 p31", real=True)
Mb = sp.Matrix([[b00, b01], [b10, b11]])
P3v = sp.Matrix([p30, p31])
X1 = X_of(s1 + D1, s2 + D2, s3 + D3)
check_zero("D lambda = M_bary DX",
           (Mb * (X1 - P3v) - Mb * (X0 - P3v) - Mb * dX).norm())

# ---------------------------------------------------------------------------
print("7. Per-operation identities of the running error bound")
# A computed value is written as its exact value plus an error.  Under (2.5),
# fl(x op y) differs from x op y, formed from the computed operands, by at most
# v |fl(x op y)|.  These identities split each step's total error into that
# rounding and the errors already in its operands.
xa, xb, ea, eb, fr = sp.symbols("xa xb ea eb fr", real=True)
check_zero("sum: fl(xa+ea + xb+eb) - (xa + xb) = rounding + ea + eb",
           ((xa + ea + xb + eb) + fr) - (xa + xb) - (fr + ea + eb))
mk = sp.symbols("mk", real=True)
check_zero("product by an exact constant: rounding + mk * ea",
           (mk * (xa + ea) + fr) - mk * xa - (fr + mk * ea))
check_zero("square: fl((xa+ea)^2) - xa^2 = rounding + ea (2 (xa+ea) - ea)",
           ((xa + ea) ** 2 + fr) - xa**2 - (fr + ea * (2 * (xa + ea) - ea)))
# The rounding term is at most v |fl(x op y)| <= v (magnitude + err), so the total
# error err of one step satisfies err <= v (magnitude + err) + e_in.  Solving for
# err gives err <= (v magnitude + e_in) / (1 - v), which is what the code uses.
mag, e_in = sp.symbols("magnitude e_in", positive=True)
err_solved = (v * mag + e_in) / (1 - v)
check_zero("err = (v mag + e_in)/(1 - v) solves err = v (mag + err) + e_in",
           err_solved - (v * (mag + err_solved) + e_in))
# The float-float closed form uses the same identities with u_f for v.  Its
# constants are float64 values split into float-float, so a constant k enters
# as k (1 + delta_k), |delta_k| <= delta_s, which adds delta_s |k x| to a
# product and delta_s |k| to a difference with k.
dk = sp.symbols("dk", real=True)
check_zero("product by a split constant: rounding + mk ea + mk dk (xa + ea)",
           (mk * (1 + dk) * (xa + ea) + fr) - mk * xa
           - (fr + mk * ea + mk * dk * (xa + ea)))
check_zero("difference with a split constant: rounding + mk dk - ea",
           ((mk * (1 + dk) - (xa + ea)) + fr) - (mk - xa) - (fr + mk * dk - ea))

# ---------------------------------------------------------------------------
print("8. A stored z gives z^2 back within gamma_3(v)")
zeta, d7, d8 = sp.symbols("zeta d7 d8", positive=True)
z_stored = sp.sqrt(zeta) * d7                           # fl(sqrt(zeta)), d7 = 1 + delta
check_zero("fl(z z) = zeta (1 + delta7)^2 (1 + delta8), three factors",
           (z_stored * z_stored) * d8 - zeta * d7**2 * d8)
# The WGSL device: z = zeta rsqrt(zeta) (1 + delta), with the reciprocal square
# root within rho and the product within u_f, for zeta >= 2^-60.  The host
# forms the float64 value of its two float32 parts with one rounding (a low
# part far below the high part spans more than 53 bits), and squares it with
# one more.  So z^2 carries (1 + rho)^2 (1 + u_f)^2 (1 + v)^3, and below 2^-60
# the device returns 0, off by at most 2^-60 in z^2.  A coordinate returned the
# same way carries one rounding v of its magnitude.
g_r, h_m, d9 = sp.symbols("g_r h_m d9", positive=True)
z_ff = zeta / sp.sqrt(zeta) * g_r * h_m * d9            # d9 = 1 + delta of hi + lo
check_zero("fl(z_ff z_ff) = zeta g_r^2 h_m^2 d9^2 (1 + delta8)",
           (z_ff * z_ff) * d8 - zeta * g_r**2 * h_m**2 * d9**2 * d8)

# ---------------------------------------------------------------------------
print("9. The assembled bound vanishes when u and v do")
cos_host, one_minus_host, X_norm, fro, z2_host, K_dev, K_host = sp.symbols(
    "cos_host one_minus_host X_norm fro z2_host K_dev K_host", positive=True)
# The host adds a run of r lengths and then the two root-child lengths of one
# split in float64: r additions in all, so gamma_r(v).
g_run64 = gamma(r, v)
comp = sp.Rational(21, 10) * v                          # (4.10), n^2 v <= 0.1
a_hi_dev = (1 + g_run32) ** 2 * (1 + gamma(n_a + 2, v))
b_lo_dev = (1 - g_run32) * (1 - u) * (1 - gamma(n_b + 1, v))
c_hi_dev = (1 + u) ** 2 * (1 + gamma(n_c - 1, v))
F_lo_dev = b_lo_dev * (1 - v) / (sp.sqrt(a_hi_dev * c_hi_dev * (1 + v)) * (1 + v))
a_lo_host = (1 - g_run64) ** 2 * (1 - v) * (1 - comp)
a_hi_host = (1 + g_run64) ** 2 * (1 + v) * (1 + comp)
b_lo_host = (1 - g_run64) * (1 - v) * (1 - comp)
b_hi_host = (1 + g_run64) * (1 + v) * (1 + comp)
c_lo_host = (1 - v) * (1 - comp)
c_hi_host = (1 + v) * (1 + comp)
F_hi_host = b_hi_host * (1 + v) / (sp.sqrt(a_lo_host * c_lo_host * (1 - v)) * (1 - v))
F_lo_host = b_lo_host * (1 - v) / (sp.sqrt(a_hi_host * c_hi_host * (1 + v)) * (1 + v))
rho_dev = sp.Max(F_hi_dev - 1, 1 - F_lo_dev)
rho_host = sp.Max(F_hi_host - 1, 1 - F_lo_host)
d_cos = cos_host / F_lo_host * (rho_dev + rho_host)
d_length = d_cos + v * (2 * one_minus_host + d_cos)
length_dev = (one_minus_host + d_cos) * (1 + v)
length_host = one_minus_host * (1 + v)
d_s2 = W * (d_length + gamma(2, v) * (length_dev + length_host)) + 2 * v * T
# One anchor's bound stands for all three here; the code carries three.
d_X = fro * sp.sqrt((d_s2 + d_s2) ** 2 + (d_s2 + d_s2) ** 2)
d_c = d_s2 + 2 * (X_norm + v * K_host) * d_X + d_X**2
running = v * (K_dev + K_host)
bound = (d_c + running) + gamma(3, v) * (z2_host + d_c + running)
check_zero("bound at u = v = 0", bound.subs({u: 0, v: 0}))
# The float-float cosine factor and the stored z vanish in the same limit.
a_hi_ff = (1 + g_run32) ** 2 * (1 + gamma(n_a, u_f))
b_lo_ff = (1 - g_run32) * (1 - u) * (1 - gamma(n_b, u_f))
c_hi_ff = (1 + u) ** 2 * (1 + gamma(n_c - 1, v)) * (1 + delta_s)
F_lo_ff = b_lo_ff * (1 - rho) ** 2 * (1 - u_f) ** 2 / sp.sqrt(a_hi_ff * c_hi_ff)
zero = {u: 0, v: 0, u_f: 0, rho: 0, delta_s: 0}
check_zero("float-float cosine factor at zero unit roundoffs, high side",
           F_hi_ff.subs(zero) - 1)
check_zero("float-float cosine factor at zero unit roundoffs, low side",
           F_lo_ff.subs(zero) - 1)
check_zero("float-float stored z at zero unit roundoffs",
           ((1 + rho) ** 2 * (1 + u_f) ** 2 * (1 + v) ** 3 - 1).subs(zero))

print("\nThe residual rounding bound is verified.")
