# Tactiverge Academy — companion code for "Numerical stability and choosing a step size"
# Lesson: https://tactiverge.win/academy/computational-engineering/scientific-simulation/stability-and-step-size/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
K_RATE = 10.0   # decay rate, per second: dy/dt = -10·y

for dt in [0.05, 0.15, 0.25]:
    y = 1.0
    values = []
    for _ in range(6):
        y = y + (-K_RATE * y) * dt      # one Euler step
        values.append(f"{y:8.3f}")
    print(f"dt = {dt:4.2f} (k·dt = {K_RATE * dt:.1f}):", " ".join(values))


# ── Example 2 ────────────────────────────────────────
M, K = 0.5, 20.0      # kg, N/m (no damping)
DT = 0.01             # s
STEPS = 1000          # 10 seconds

def energy(x, v):
    return 0.5 * M * v * v + 0.5 * K * x * x   # joules

def explicit_euler(x, v):
    a = -K * x / M
    return x + v * DT, v + a * DT          # both use OLD values

def semi_implicit_euler(x, v):
    a = -K * x / M
    v = v + a * DT                         # update velocity first...
    return x + v * DT, v                   # ...then position uses NEW v

for name, step in [("explicit", explicit_euler), ("semi-implicit", semi_implicit_euler)]:
    x, v = 0.10, 0.0
    e0 = energy(x, v)
    for _ in range(STEPS):
        x, v = step(x, v)
    print(f"{name:14s} energy after 10 s: {energy(x, v) / e0:7.3f} × start")
