# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Compare BDF2 and backward Euler after a fast transient."""

from math import exp
from pathlib import Path
import sys

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "reference"))
from bdf2 import integrate, start

f = lambda t, y: (-y[0], -1e4*y[1])
J = lambda t, y: ((-1, 0), (0, -1e4))
y0, h = (1.0, 1.0), 0.025
for _, y in integrate(f, J, 0, y0, h, 40):
    pass
be = y0
for n in range(40):
    be = start(f, J, n*h, be, h)
print("Slow decay after a fast transient at t=1")
print(f"BDF2 slow error: {abs(y[0]-exp(-1)):.3e}")
print(f"Backward Euler slow error: {abs(be[0]-exp(-1)):.3e}")
print(f"Fast component practically gone: {abs(y[1]) < 1e-12}")
