# Tactiverge Academy — companion code for "Time stepping with Euler's method"
# Lesson: https://tactiverge.win/academy/computational-engineering/scientific-simulation/eulers-method/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
import math

RC = 2.0    # time constant, seconds
V0 = 5.0    # starting voltage, volts

def dVdt(t, V):
    return -V / RC

def euler(f, y0, t_end, dt):
    """Step dy/dt = f(t, y) from t = 0 to t_end with Euler's method."""
    steps = round(t_end / dt)
    t, y = 0.0, y0
    for _ in range(steps):
        y = y + f(t, y) * dt
        t = t + dt
    return y

exact = V0 * math.exp(-4.0 / RC)
print(f"exact V(4) = {exact:.4f} V")
for dt in [0.5, 0.25, 0.125, 0.0625]:
    v = euler(dVdt, V0, 4.0, dt)
    print(f"dt = {dt:<6}  V(4) = {v:.4f} V   error = {v - exact:+.4f} V")


# ── Example 2 ────────────────────────────────────────
G = 9.81  # m/s²

def derivatives(state):
    """Rates of change for a dropped object: (dy/dt, dv/dt)."""
    y, v = state          # distance fallen (m), downward speed (m/s)
    return (v, G)

def euler_step(state, dt):
    rates = derivatives(state)
    return tuple(s + r * dt for s, r in zip(state, rates))

state = (0.0, 0.0)
dt = 0.1
for _ in range(20):       # 20 steps of 0.1 s = 2.0 s
    state = euler_step(state, dt)

y, v = state
print(f"Euler: fallen {y:.3f} m, speed {v:.3f} m/s")
print(f"Exact: fallen {0.5 * G * 2.0**2:.3f} m, speed {G * 2.0:.3f} m/s")
