Worked solutions to the three exercises of Lecture 0. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
heading("Demonstration 1: IEEE-754 bit inspection, ULP stairstep and non-associativity")
probe_vals = [0.1, 1.0, 1.0e16, -0.0, 2.0 ** (-1074), math.inf]
print(f"{'Value':>12s} | {'Kind':>9s} | {'Sign':>4s} | {'Unbiased e':>10s} | {'ULP Spacing':>13s} | {'High Bits (s|exp|mant...)':>28s}")
print("-" * 92)
for val in probe_vals:
info = representation_scaling.ieee754_float64_inspect(val)
b64 = info["bitstring_64"]
pretty_bits = f"{b64[0]}|{b64[1:12]}|{b64[12:24]}..."
e_str = str(info["unbiased_exponent"])
print(f"{str(val):>12s} | {info['kind']:>9s} | {info['sign_bit']:4d} | {e_str:>10s} | {info['ulp']:13.4e} | {pretty_bits:>28s}")
# Demonstrate absorption at 1e16 (where ulp = 2.0) and violation of (a + b) + c == a + (b + c):
ulp_1e16 = representation_scaling.ieee754_float64_inspect(1.0e16)["ulp"]
lhs_assoc = (1.0e16 + (-1.0e16)) + 1.0
rhs_assoc = 1.0e16 + (-1.0e16 + 1.0)
print(f"\nAt x = 1e16: ulp(1e16) = {ulp_1e16:.1f} -> (1e16 + 1.0 == 1e16) is {1.0e16 + 1.0 == 1.0e16}")
print(f"Associativity test: ((1e16 + -1e16) + 1.0) = {lhs_assoc:.1f} != (1e16 + (-1e16 + 1.0)) = {rhs_assoc:.1f}")
x_dense = np.linspace(0.5, 8.0, 600)
ulps_dense = np.array([representation_scaling.ieee754_float64_inspect(float(v))["ulp"] for v in x_dense])
x_wide = 10.0 ** np.linspace(-15, 18, 200)
ulps_wide = np.array([representation_scaling.ieee754_float64_inspect(float(v))["ulp"] for v in x_wide])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.2))
ax1.step(x_dense, ulps_dense / (2.0 ** -52), where="post", color="#2166AC", lw=2.1, label=r"$\mathrm{ulp}(x) / \varepsilon_{\mathrm{mach}}$")
ax1.plot(x_dense, ulps_dense / x_dense / (2.0 ** -52), color="#C0392B", lw=1.6, ls="--", label=r"Relative spacing $(\mathrm{ulp}(x)/x)/\varepsilon_{\mathrm{mach}}$")
ax1.set_xlabel(r"Magnitude $x$")
ax1.set_ylabel(r"Normalized spacing (units of $\varepsilon_{\mathrm{mach}} = 2^{-52}$)")
ax1.set_title("Spacing of float64 numbers near 1")
ax1.legend(fontsize=8.2)
ax2.loglog(x_wide, ulps_wide, color="#2E8B57", lw=2.2, label=r"Exact $\mathrm{ulp}(x)$")
ax2.axhline(1.0, color="gray", ls=":", lw=1.4, label=r"Unit gap $\mathrm{ulp} = 1.0$ ($|x| \approx 4.5 \times 10^{15}$)")
ax2.set_xlabel(r"Magnitude $|x|$")
ax2.set_ylabel(r"Absolute gap $\mathrm{ulp}(x)$")
ax2.set_title("Absolute spacing over 33 decades")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
assert ulp_1e16 == 2.0
assert lhs_assoc == 1.0 and rhs_assoc == 0.0
assert representation_scaling.ieee754_float64_inspect(2.0 ** -1074)["kind"] == "subnormal"
assert representation_scaling.ieee754_float64_inspect(-0.0)["sign_bit"] == 1
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Prove via fractions.Fraction(0.1) that IEEE-754 0.1 exceeds by exactly , and compare cumulative clock error over 100 hours ( ticks of ) across Patriot’s 24-bit signed fixed-point register (1 sign bit + 23 fractional bits), float64 t += 0.1 accumulation, and integer tick counting k * 0.1.
heading("Exercise 1: Exact binary excess of 0.1 and Patriot 100-hour range-gate drift")
from fractions import Fraction
f_01 = Fraction(0.1)
exact_tenth = Fraction(1, 10)
excess_01 = f_01 - exact_tenth
expected_excess = Fraction(1, 5 * (2 ** 55))
print(f"Fraction(0.1) = {f_01.numerator} / 2^55")
print(f"Exact excess over 1/10 = {excess_01} == +1 / (5 * 2^55) ({float(excess_01):+.6e} s)")
assert excess_01 == expected_excess
# Patriot 24-bit signed fixed-point register (1 sign bit + 23 fractional bits) chopped 1/10 to 23 bits:
patriot_step = Fraction(int(Fraction(1, 10) * (2 ** 23)), 2 ** 23) # 838860 / 8388608
patriot_tick_err = exact_tenth - patriot_step # 1 / 10485760 s/tick = 9.53674e-8 s
n_ticks_100h = 100 * 3600 * 10 # 3,600,000 tenths of a second
patriot_drift_s = float(n_ticks_100h * patriot_tick_err)
scud_miss_m = patriot_drift_s * 1676.0
# Compare repeated float64 addition vs integer tick multiplication over 3,600,000 steps:
t_accum = 0.0
for _ in range(n_ticks_100h):
t_accum += 0.1
float64_accum_err_s = abs(t_accum - 360000.0)
integer_tick_err_s = abs((n_ticks_100h * 0.1) - 360000.0)
print(f"\nAfter 100 hours ({n_ticks_100h:,d} ticks of 0.1 s = 360,000.0 s):")
print(f" (a) Patriot 24-bit chopped drift : {patriot_drift_s:.6f} s -> Scud miss @ 1676 m/s = {scud_miss_m:.1f} m")
print(f" (b) float64 loop `t += 0.1` err : {float64_accum_err_s:.6e} s")
print(f" (c) Integer tick `k * 0.1` err : {integer_tick_err_s:.6e} s")
assert patriot_tick_err == Fraction(4, 5 * (2 ** 23))
assert 0.343 < patriot_drift_s < 0.344 and scud_miss_m > 570.0
assert float64_accum_err_s > 1.0e-6 and integer_tick_err_s == 0.0
Exercise 1: Exact binary excess of 0.1 and Patriot 100-hour range-gate drift
============================================================================
Fraction(0.1) = 3602879701896397 / 2^55
Exact excess over 1/10 = 1/180143985094819840 == +1 / (5 * 2^55) (+5.551115e-18 s)
After 100 hours (3,600,000 ticks of 0.1 s = 360,000.0 s):
(a) Patriot 24-bit chopped drift : 0.343323 s -> Scud miss @ 1676 m/s = 575.4 m
(b) float64 loop `t += 0.1` err : 1.201301e-05 s
(c) Integer tick `k * 0.1` err : 0.000000e+00 s
Explanation. Because has prime factor , is an infinite repeating binary fraction. Chopping after 23 fractional bits loses every tick, growing linearly over ticks to (a Scud travels in that time). Storing time as an integer tick counter k and converting k * dt on demand eliminates cumulative drift completely.
Exercise 2¶
Problem. Quantify catastrophic digit loss in the textbook quadratic root for across relative to Vieta’s Citardauq invariant , and audit naive np.log(np.sum(np.exp(z))) at .
heading("Exercise 2: Catastrophic quadratic root cancellation and naive LogSumExp failure")
from fractions import Fraction
b_vals = -(10.0 ** np.arange(4, 10, dtype=float))
err_textbook, err_vieta = [], []
print(f"{'b':>11s} | {'Textbook x2':>18s} | {'Vieta c/(a*x1)':>18s} | {'Textbook RelErr':>15s} | {'Vieta RelErr':>13s}")
print("-" * 86)
for b in b_vals:
disc = math.sqrt(b * b - 4.0)
x1_stable = (-b + disc) / 2.0 # Since -b > 0, both terms are positive (zero cancellation)
x2_naive = (-b - disc) / 2.0 # Subtracts nearly equal numbers when b^2 >> 4
x2_vieta = 1.0 / x1_stable # Vieta's product invariant x1 * x2 = c / a = 1
# High-precision reference via 2-term Newton polish in exact Fraction arithmetic:
fb = Fraction(int(b))
x_q = Fraction(1, -int(b))
for _ in range(3):
x_q = x_q - (x_q * x_q + fb * x_q + 1) / (2 * x_q + fb)
x2_true = float(x_q)
en = max(abs(x2_naive - x2_true) / x2_true, 1.0e-17)
ev = max(abs(x2_vieta - x2_true) / x2_true, 1.0e-17)
err_textbook.append(en)
err_vieta.append(ev)
print(f"{b:11.1e} | {x2_naive:18.10e} | {x2_vieta:18.10e} | {en:15.2e} | {ev:13.2e}")
with np.errstate(over="ignore", divide="ignore"):
lse_hi_bad = float(np.log(np.sum(np.exp(np.array([800.0, 801.0, 802.0])))))
lse_lo_bad = float(np.log(np.sum(np.exp(np.array([-800.0, -799.0, -798.0])))))
lse_hi_ok = representation_scaling.stable_logsumexp(np.array([800.0, 801.0, 802.0]))["log_sum_exp"]
lse_lo_ok = representation_scaling.stable_logsumexp(np.array([-800.0, -799.0, -798.0]))["log_sum_exp"]
print(f"\nNaive LSE(+800..802) = {lse_hi_bad} vs Stable = {lse_hi_ok:.6f}")
print(f"Naive LSE(-800..-798) = {lse_lo_bad} vs Stable = {lse_lo_ok:.6f}")
assert err_textbook[-1] == 1.0 and err_vieta[-1] < 1.0e-15
assert math.isinf(lse_hi_bad) and lse_hi_bad > 0
assert math.isinf(lse_lo_bad) and lse_lo_bad < 0
assert np.isclose(lse_hi_ok - 800.0, lse_lo_ok + 800.0, atol=1e-12)
Exercise 2: Catastrophic quadratic root cancellation and naive LogSumExp failure
================================================================================
b | Textbook x2 | Vieta c/(a*x1) | Textbook RelErr | Vieta RelErr
--------------------------------------------------------------------------------------
-1.0e+04 | 1.0000000111e-04 | 1.0000000100e-04 | 1.12e-09 | 1.00e-17
-1.0e+05 | 1.0000003385e-05 | 1.0000000001e-05 | 3.38e-07 | 1.69e-16
-1.0e+06 | 1.0000076145e-06 | 1.0000000000e-06 | 7.61e-06 | 1.00e-17
-1.0e+07 | 9.9651515484e-08 | 1.0000000000e-07 | 3.48e-03 | 1.00e-17
-1.0e+08 | 7.4505805969e-09 | 1.0000000000e-08 | 2.55e-01 | 1.00e-17
-1.0e+09 | 0.0000000000e+00 | 1.0000000000e-09 | 1.00e+00 | 1.00e-17
Naive LSE(+800..802) = inf vs Stable = 802.407606
Naive LSE(-800..-798) = -inf vs Stable = -797.592394
Explanation. At , has , so identically and the textbook numerator collapses to 0.0 ( relative error). Computing the non-cancelling root first and recovering via Vieta’s invariant maintains full 16-digit accuracy across every scale.
Exercise 3¶
Problem. Implement compensated_dot_and_pairwise_sum(a, b) returning np_dot, pairwise_dot, dot2_compensated, and exact_dot using recursive pairwise product summation and Ogita–Rump–Oishi’s error-free Dot2 transformation (two_prod via Veltkamp splitting and Knuth two_sum). Verify on an ill-conditioned dot product with condition number .
heading("Exercise 3: Implement it yourself — Ogita-Rump-Oishi Dot2 and pairwise summation")
from fractions import Fraction
def _two_sum(a: float, b: float) -> tuple[float, float]:
"""Knuth error-free transformation: a + b == x + y exactly in IEEE-754."""
x = a + b
z = x - a
y = (a - (x - z)) + (b - z)
return x, y
def _split_veltkamp(a: float) -> tuple[float, float]:
"""Split 53-bit float64 significand into 26-bit high and 27-bit low parts (2^27 + 1 = 134217729)."""
c = 134217729.0 * a
a_hi = c - (c - a)
a_lo = a - a_hi
return a_hi, a_lo
def _two_prod(a: float, b: float) -> tuple[float, float]:
"""Dekker/Veltkamp error-free product: a * b == x + y exactly without hardware FMA."""
x = a * b
a_hi, a_lo = _split_veltkamp(a)
b_hi, b_lo = _split_veltkamp(b)
y = a_lo * b_lo - (((x - a_hi * b_hi) - a_lo * b_hi) - a_hi * b_lo)
return x, y
def _pairwise_recursive_sum(arr: np.ndarray) -> float:
n = arr.size
if n == 0:
return 0.0
if n <= 8:
s = 0.0
for v in arr:
s += float(v)
return s
mid = n // 2
return _pairwise_recursive_sum(arr[:mid]) + _pairwise_recursive_sum(arr[mid:])
def compensated_dot_and_pairwise_sum(a: np.ndarray, b: np.ndarray) -> dict:
"""Compare standard dot, pairwise product sum, and Ogita-Rump-Oishi Dot2 against exact rational dot."""
va = np.asarray(a, dtype=np.float64).ravel()
vb = np.asarray(b, dtype=np.float64).ravel()
if va.size != vb.size or va.size == 0:
raise ValueError("Require equal-length non-empty 1-D vectors.")
prods = va * vb
pw_dot = _pairwise_recursive_sum(prods)
p, s = _two_prod(float(va[0]), float(vb[0]))
for i in range(1, va.size):
h, r = _two_prod(float(va[i]), float(vb[i]))
p, q = _two_sum(p, h)
s += q + r
dot2 = p + s
exact_q = sum(Fraction(float(x)) * Fraction(float(y)) for x, y in zip(va, vb))
exact_val = float(exact_q)
cond_num = float(np.sum(np.abs(va * vb))) / max(abs(exact_val), 1.0e-300)
return {
"np_dot": float(np.dot(va, vb)),
"pairwise_dot": pw_dot,
"dot2_compensated": dot2,
"exact_dot": exact_val,
"condition_number": cond_num,
}
# Construct ill-conditioned dot product (large 53-bit cancelling pairs + subtle signal, kappa > 1e14):
rng_d = np.random.default_rng(7)
m_half = 256
u_big = rng_d.normal(0.0, 2.0e6, size=m_half)
v_big = rng_d.normal(0.0, 2.0e6, size=m_half)
u_small = rng_d.uniform(0.5, 1.5, size=32)
v_small = rng_d.uniform(0.02, 0.05, size=32)
vec_a = np.concatenate([u_big, u_big, u_small])
vec_b = np.concatenate([v_big, -v_big, v_small])
perm = rng_d.permutation(vec_a.size)
vec_a, vec_b = vec_a[perm], vec_b[perm]
dot_bench = compensated_dot_and_pairwise_sum(vec_a, vec_b)
err_np = abs(dot_bench["np_dot"] - dot_bench["exact_dot"]) / abs(dot_bench["exact_dot"])
err_pw = abs(dot_bench["pairwise_dot"] - dot_bench["exact_dot"]) / abs(dot_bench["exact_dot"])
err_d2 = abs(dot_bench["dot2_compensated"] - dot_bench["exact_dot"]) / abs(dot_bench["exact_dot"])
print(f"Condition number kappa = {dot_bench['condition_number']:.2e}")
print(f"Exact rational dot = {dot_bench['exact_dot']:+.15f}")
print(f"np.dot = {dot_bench['np_dot']:+.15f} (rel err = {err_np:.2e})")
print(f"Pairwise product sum = {dot_bench['pairwise_dot']:+.15f} (rel err = {err_pw:.2e})")
print(f"Ogita-Rump-Oishi Dot2 = {dot_bench['dot2_compensated']:+.15f} (rel err = {err_d2:.2e})")
assert dot_bench["condition_number"] > 1.0e13
assert err_np > 1.0e-5 and err_d2 < 1.0e-14
Exercise 3: Implement it yourself — Ogita-Rump-Oishi Dot2 and pairwise summation
================================================================================
Condition number kappa = 1.04e+15
Exact rational dot = +1.047532390137765
np.dot = +1.041015625000000 (rel err = 6.22e-03)
Pairwise product sum = +1.046875000000000 (rel err = 6.28e-04)
Ogita-Rump-Oishi Dot2 = +1.047532390137765 (rel err = 0.00e+00)
Summary. Pairwise summation improves summation error growth from to , yet it cannot recover low-order product bits already lost inside each rounded a[i] * b[i]. Ogita–Rump–Oishi’s Dot2 captures both product rounding (_two_prod) and addition rounding (_two_sum) into a single scalar accumulator s, achieving simulated quadruple-precision () accuracy in pure float64.