# Tactiverge Academy — companion code for "Simulating a falling object with air drag"
# Lesson: https://tactiverge.win/academy/computational-engineering/scientific-simulation/falling-object-with-drag/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

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

G = 9.81          # m/s²
RHO = 1.2         # air density, kg/m³ (room conditions, assumed)
CD = 0.47         # drag coefficient of a smooth sphere (typical value)
MASS = 0.0027     # kg, a table-tennis ball
DIAMETER = 0.040  # m
AREA = math.pi * (DIAMETER / 2) ** 2

def acceleration(v):
    """Downward acceleration: gravity minus drag (v is downward speed)."""
    drag = 0.5 * RHO * CD * AREA * v * v     # newtons, opposes motion
    return G - drag / MASS

def drop(height, dt):
    """Return (time, impact speed) for a ball dropped from rest."""
    t, y, v = 0.0, 0.0, 0.0                  # y = distance fallen
    while y < height:
        a = acceleration(v)
        y = y + v * dt
        v = v + a * dt
        t = t + dt
    return t, v

v_terminal = math.sqrt(2 * MASS * G / (RHO * CD * AREA))
print(f"terminal speed: {v_terminal:.2f} m/s")

t, v = drop(10.0, 0.001)
print(f"with drag:    lands after {t:.2f} s at {v:.2f} m/s")
t0 = math.sqrt(2 * 10.0 / G)
print(f"without drag: lands after {t0:.2f} s at {G * t0:.2f} m/s")


# ── Example 2 ────────────────────────────────────────
import math

G, RHO, CD, MASS = 9.81, 1.2, 0.47, 0.0027
AREA = math.pi * 0.020 ** 2
C = 0.5 * RHO * CD * AREA                # drag constant, kg/m
VT = math.sqrt(MASS * G / C)              # terminal speed

dt = 0.01
v = 0.0
print("  t (s)   Euler v   exact v   (m/s)")
for step in range(1, 301):                # 3 seconds
    v = v + (G - C * v * v / MASS) * dt
    if step % 50 == 0:
        t = step * dt
        exact = VT * math.tanh(G * t / VT)
        print(f"  {t:4.1f}   {v:7.3f}   {exact:7.3f}")
