# Logistic map x -> 4x(1-x) in IEEE single precision (float32).
# For each random initial condition, iterate until the orbit reaches 0
# or revisits a value (a periodic cycle).  Rob, November 7, 2026
import numpy as np, random
f32 = np.float32
def step(x, mode):
    if mode == 'pure':  return f32(4)*x*(f32(1)-x)                # every operation rounded
    if mode == 'once':  return f32(4.0*float(x)*(1.0-float(x)))   # exact, then rounded once
    z = 4.0*float(x)*(1.0-float(x))                               # 'dither': tiny random noise
    if z < 0.999: z *= 1.0 + 1e-7*(random.random()-0.5)
    return f32(z)
def run(mode, cases=10000, seed=1):
    random.seed(seed); zero = []; cycles = 0
    for _ in range(cases):
        x = f32(random.random()); seen = set(); n = 0
        while x != 0:
            if mode != 'dither':
                if x in seen: cycles += 1; break
                seen.add(x)
            x = step(x, mode); n += 1
        else: zero.append(n)
    print(f"{mode:6s}: {len(zero)} reached 0, average N = {np.mean(zero):.0f}, "
          f"{100*cycles/cases:.1f}% caught in cycles")
for mode in ('pure', 'once', 'dither'): run(mode)
