# Tactiverge Academy — companion code for "Simulating a spring–mass–damper system"
# Lesson: https://tactiverge.win/academy/computational-engineering/scientific-simulation/spring-mass-damper/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

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

M = 0.5    # kg
K = 20.0   # N/m
C_CRIT = 2 * math.sqrt(K * M)   # critical damping, N·s/m

def simulate(c, x0=0.10, t_end=3.0, dt=0.0001, report_every=0.5):
    """Explicit Euler for m·x'' + c·x' + k·x = 0. Returns reported (t, x)."""
    x, v = x0, 0.0
    out = []
    steps = round(t_end / dt)
    every = round(report_every / dt)
    for step in range(1, steps + 1):
        a = (-K * x - c * v) / M
        x, v = x + v * dt, v + a * dt
        if step % every == 0:
            out.append((step * dt, x))
    return out

print(f"natural frequency: {math.sqrt(K / M):.3f} rad/s, "
      f"period {2 * math.pi / math.sqrt(K / M):.3f} s")
print(f"critical damping:  {C_CRIT:.3f} N·s/m")
for zeta in [0.1, 1.0, 2.0]:
    rows = simulate(zeta * C_CRIT)
    xs = "  ".join(f"{x * 1000:6.1f}" for _, x in rows)
    print(f"zeta = {zeta}: x (mm) at 0.5 s steps: {xs}")
