"""Compare a confined return in exact fractions and binary floating point.

Run with Python 3. The initial pair, four strengths and all dyadic
perturbations used as inputs are exactly representable in binary64.
"""

from fractions import Fraction


def fourth_value(previous, current, strengths):
    for strength in strengths:
        following = strength / current - current - previous
        previous, current = current, following
    return current


def main():
    previous = Fraction(3, 2)
    strengths = [Fraction(n, 2) for n in (5, 5, 9, 9)]
    expected = strengths[0] * previous / strengths[-1]
    assert expected == Fraction(5, 6)

    print("k   exact x4 (rounded)      float x4")
    last_error = None
    for k in (10, 14, 18, 20):
        epsilon = Fraction(1, 2**k)
        exact = fourth_value(previous, epsilon, strengths)
        floating = fourth_value(float(previous), float(epsilon),
                                [float(value) for value in strengths])
        error = abs(exact - expected)
        assert last_error is None or error < last_error
        last_error = error
        print(f"{k:2d}  {float(exact):18.12f}  {floating:18.12f}")

    # The leading pole reappears if only the final strength changes by one.
    broken = strengths[:-1] + [strengths[-1] + 1]
    residue = -strengths[0] / strengths[-1]
    scaled_return = epsilon * fourth_value(previous, epsilon, broken)
    assert abs(scaled_return - residue) < 10 * epsilon
    print(f"Confined limit: {expected}; changed last strength: "
          f"epsilon*x4 = {float(scaled_return):.9f}, approaching {residue}.")


if __name__ == "__main__":
    main()
