TExcelTAD
Home › Calculus in Depth › Mini Project: A Physics and Optimization Toolkit

Mini Project: A Physics and Optimization Toolkit

In this project you will build a small numerical toolkit in Python, one function at a time, and then use all of it together on a real problem: at what angle must you kick a ball, against air resistance, so that it lands exactly on a target? The toolkit has four parts, each an idea from this course turned into code: numerical derivatives and gradients, Simpson's rule, the fourth-order Runge-Kutta method (RK4) for differential equations, and gradient descent with a backtracking line search.

It pulls together Numerical Calculus and Floating Point, Approximate Integration, Direction Fields and Euler's Method, Motion in Space, Directional Derivatives and the Gradient Vector and Applications of Second-Order Equations.

What we are building: a set of functions derivative, gradient, simpson, simpson_samples, rk4_step, rk4 and minimize, each tested against a problem with a known answer, and a fly function that simulates a ball with quadratic drag.

Step New concepts
1. Derivatives and gradients central differences, relative step size, testing against exact derivatives
2. Simpson's rule composite Simpson, the O(h4)O(h^4) error check, integrating sampled data
3. RK4 systems of first-order ODEs, a second-order equation as a system, projectile with drag
4. Gradient descent with line search the Armijo condition, why a fixed step fails on a stretched bowl
5. The targeting problem a miss function built from a simulation, two solutions, maximum range, an energy check

Note: Every step is a complete program. Steps 2 to 4 repeat only the functions they use; step 5 contains the whole toolkit, so it is the file to keep. The code favours clarity over speed: a real engine would vectorise or use scipy.integrate.solve_ivp and scipy.optimize.

Step 1: Derivatives and gradients

The central difference f(x+h)−f(x−h)2h\frac{f(x + h) - f(x - h)}{2h} has error O(h2)O(h^2), and with hh near ε3≈10−5\sqrt[3]{\varepsilon} \approx 10^{-5} it balances truncation against rounding. Scaling hh by max⁡(1,∣x∣)\max(1, \lvert x \rvert) keeps the step relative to the size of xx, so the same code works at x=0.001x = 0.001 and at x=106x = 10^6. The gradient applies the same quotient to one coordinate at a time.

python · try it yourself
import math
import numpy as np

def derivative(f, x, h=1e-5):
    h = h * max(1.0, abs(x))                     # relative step
    return (f(x + h) - f(x - h)) / (2 * h)

def gradient(f, x, h=1e-5):
    x = np.asarray(x, dtype=float)
    g = np.zeros_like(x)
    for i in range(x.size):
        e = np.zeros_like(x)
        e[i] = h * max(1.0, abs(x[i]))
        g[i] = (f(x + e) - f(x - e)) / (2 * e[i])
    return g

print(f"d/dx sin x at 1    : {derivative(math.sin, 1.0):.10f}   exact {math.cos(1.0):.10f}")
print(f"d/dx e^x at 20     : {derivative(math.exp, 20.0):.6e}   exact {math.exp(20.0):.6e}")
f = lambda p: p[0]**2 * p[1] + math.exp(p[1])          # gradient (2xy, x^2 + e^y)
print("grad f at (1, 0)   :", np.round(gradient(f, [1.0, 0.0]), 8), "  exact [0. 2.]")
print("grad f at (2, 1)   :", np.round(gradient(f, [2.0, 1.0]), 6), "  exact", np.round([4.0, 4 + math.e], 6))
d/dx sin x at 1    : 0.5403023059   exact 0.5403023059
d/dx e^x at 20     : 4.851652e+08   exact 4.851652e+08
grad f at (1, 0)   : [0. 2.]   exact [0. 2.]
grad f at (2, 1)   : [4.       6.718282]   exact [4.       6.718282]

Both derivatives agree with the exact values to about ten significant digits, which is what the error analysis predicts.

Step 2: Simpson's rule

Composite Simpson fits a parabola through each pair of subintervals: h3[f0+4f1+2f2+4f3+⋯+fn]\frac{h}{3}[f_0 + 4f_1 + 2f_2 + 4f_3 + \cdots + f_n]. Its error is O(h4)O(h^4), so doubling nn should divide the error by about 16. That ratio is the test. A second version, simpson_samples, integrates equally spaced data (such as the samples a simulation produces) instead of a function.

python · try it yourself
import math
import numpy as np

def simpson(f, a, b, n=100):
    n += n % 2                                   # n must be even
    h = (b - a) / n
    s = f(a) + f(b) + sum((4 if k % 2 else 2) * f(a + k * h) for k in range(1, n))
    return s * h / 3

def simpson_samples(ys, h):
    ys = np.asarray(ys, dtype=float)             # an odd number of equally spaced samples
    return h / 3 * (ys[0] + ys[-1] + 4 * ys[1:-1:2].sum() + 2 * ys[2:-1:2].sum())

previous = None
for n in [4, 8, 16, 32]:
    err = abs(simpson(math.sin, 0, math.pi, n) - 2)
    ratio = f"   ratio {previous / err:5.1f}" if previous else ""
    print(f"n = {n:2d}   error {err:.3e}{ratio}")
    previous = err

t = np.linspace(0, 2, 201)                         # samples of v(t) = 3t^2, distance = t^3
print("distance from samples:", round(float(simpson_samples(3 * t**2, t[1] - t[0])), 12), "  exact 8")
n =  4   error 4.560e-03
n =  8   error 2.692e-04   ratio  16.9
n = 16   error 1.659e-05   ratio  16.2
n = 32   error 1.033e-06   ratio  16.1
distance from samples: 8.0   exact 8

The ratio settles at 16=2416 = 2^4. Simpson is exact for cubics, which is why the sampled 3t23t^2 gives 8 to every printed digit.

Step 3: RK4 for systems

RK4 advances y′=f(t,y)y' = f(t, y) by sampling the slope four times per step and averaging them with weights 1, 2, 2, 1; its global error is O(h4)O(h^4). It works on vectors, so a second-order equation becomes a first-order system by adding the velocity to the state: for a ball, s=(x,y,vx,vy)s = (x, y, v_x, v_y). Air resistance at these speeds is quadratic, a force of size K⋅∣v∣2K \cdot \lvert v \rvert^2 opposite to vv:

x′=vx,y′=vy,vx′=−KM⋅∣v∣⋅vx,vy′=−g−KM⋅∣v∣⋅vyx' = v_x, \qquad y' = v_y, \qquad v_x' = -\frac{K}{M} \cdot \lvert v \rvert \cdot v_x, \qquad v_y' = -g - \frac{K}{M} \cdot \lvert v \rvert \cdot v_y

M=0.45 kgM = 0.45\ \text{kg} and K=0.0057 kg/mK = 0.0057\ \text{kg/m} are roughly a football. Tests: one period of y′′=−yy'' = -y must return to the start, and without drag the range must match the formula v02⋅sin⁡2θ/gv_0^2 \cdot \sin 2\theta / g.

python · try it yourself
import math
import numpy as np

def rk4_step(f, t, y, h):
    k1 = f(t, y)
    k2 = f(t + h / 2, y + h / 2 * k1)
    k3 = f(t + h / 2, y + h / 2 * k2)
    k4 = f(t + h, y + h * k3)
    return y + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def rk4(f, y0, t0, h, n_steps, stop=None):
    t, y = t0, np.asarray(y0, dtype=float)
    ts, ys = [t], [y]
    for _ in range(n_steps):
        y = rk4_step(f, t, y, h)
        t += h
        ts.append(t)
        ys.append(y)
        if stop is not None and stop(y):
            break
    return np.array(ts), np.array(ys)

ts, ys = rk4(lambda t, y: np.array([y[1], -y[0]]), [1.0, 0.0], 0.0, 2 * math.pi / 100, 100)
print(f"oscillator after one period: y = {ys[-1, 0]:.10f}  (exact 1),  error {abs(ys[-1, 0] - 1):.1e}")

G, M = 9.81, 0.45
def make_ball(K):
    def ball(t, s):
        x, y, vx, vy = s
        speed = math.hypot(vx, vy)
        return np.array([vx, vy, -K / M * speed * vx, -G - K / M * speed * vy])
    return ball

v0, angle = 30.0, math.radians(40)
s0 = [0.0, 0.0, v0 * math.cos(angle), v0 * math.sin(angle)]
for K in [0.0, 0.0057]:
    ts, ys = rk4(make_ball(K), s0, 0.0, 0.01, 10_000, stop=lambda s: s[1] < 0)
    print(f"K = {K}: lands between x = {ys[-2, 0]:.2f} and {ys[-1, 0]:.2f} m after about {ts[-1]:.2f} s")
print(f"no-drag formula: {v0**2 * math.sin(2 * angle) / G:.2f} m")
oscillator after one period: y = 0.9999999573  (exact 1),  error 4.3e-08
K = 0.0: lands between x = 90.32 and 90.55 m after about 3.94 s
K = 0.0057: lands between x = 51.37 and 51.48 m after about 3.32 s
no-drag formula: 90.35 m

Drag costs the ball a large part of its range. The landing point is only bracketed here, between the last step above the ground and the first one below it; step 5 pins it down.

Step 4: Gradient descent with a line search

The update x←x−η⋅∇f(x)x \leftarrow x - \eta \cdot \nabla f(x) needs a step size η\eta. Too small and it crawls; too large and it diverges. A backtracking line search starts with a generous η\eta and halves it until the Armijo condition f(x−η∇f)≤f(x)−c⋅η⋅∣∇f∣2f(x - \eta\nabla f) \le f(x) - c \cdot \eta \cdot \lvert \nabla f \rvert^2 holds (c=10−4c = 10^{-4}), which guarantees real progress at every step. The test is a stretched bowl f=(x−3)2+25(y+1)2f = (x - 3)^2 + 25(y + 1)^2, whose minimum is (3,−1)(3, -1). A fixed step must stay below 2/50=0.042/50 = 0.04 to be stable in the steep yy direction, and then it crawls in the shallow xx direction.

python · try it yourself
import numpy as np

def gradient(f, x, h=1e-5):
    x = np.asarray(x, dtype=float)
    g = np.zeros_like(x)
    for i in range(x.size):
        e = np.zeros_like(x)
        e[i] = h * max(1.0, abs(x[i]))
        g[i] = (f(x + e) - f(x - e)) / (2 * e[i])
    return g

def minimize(f, x0, step0=1.0, tol=1e-6, max_iter=200):
    x = np.asarray(x0, dtype=float)
    for it in range(1, max_iter + 1):
        g = gradient(f, x)
        if np.linalg.norm(g) < tol:
            break
        fx, step = f(x), step0
        while f(x - step * g) > fx - 1e-4 * step * (g @ g):   # Armijo condition
            step /= 2
        x = x - step * g
    return x, it

bowl = lambda p: (p[0] - 3)**2 + 25 * (p[1] + 1)**2
x, it = minimize(bowl, [0.0, 0.0])
print("line search :", np.round(x, 6), f"after {it} iterations")

for eta in [0.01, 0.045]:
    p = np.array([0.0, 0.0])
    for k in range(200):
        p = p - eta * gradient(bowl, p)
    print(f"fixed step {eta}: {np.round(p, 6) if np.all(np.abs(p) < 1e6) else 'diverged'} after 200 iterations")
line search : [ 3. -1.] after 183 iterations
fixed step 0.01: [ 2.947236 -1.      ] after 200 iterations
fixed step 0.045: diverged after 200 iterations

The line search needed no tuning: it discovered on its own that steps above about 0.04 fail the Armijo test and settled on 1/321/32. The fixed step 0.045, only slightly too large, diverges, and the cautious 0.01 is still short of x=3x = 3 after 200 iterations. The 183 iterations themselves come from the shape of the bowl: it is 25 times steeper in yy than in xx, and any method that only follows the gradient zigzags across such a valley. Newton's method or conjugate gradients fix that, but for the one-dimensional problems of step 5 plain gradient descent is enough.

Step 5: The targeting problem

Now everything works together. fly(angle) simulates the kick with RK4 and finds the landing point by bisection inside the last step: it searches for the partial step length that puts the ball exactly at y=0y = 0, so the range is a smooth function of the angle. Then:

  1. Aim. The miss function (range(θ)−40)2(\text{range}(\theta) - 40)^2 is zero at the right angle. Starting from 20° and from 60°, minimize finds the two solutions, a flat shot and a lob.
  2. Maximum range. Minimising −range(θ)-\text{range}(\theta) gives the best angle with drag, which is below the 45° of the drag-free formula.
  3. Energy check. Drag removes energy at the rate K⋅∣v∣3K \cdot \lvert v \rvert^3 (force K∣v∣2K\lvert v \rvert^2 times speed ∣v∣\lvert v \rvert). Integrating that power with simpson_samples over the simulated velocities must equal the drop in kinetic plus potential energy over the same time span: an independent check that RK4 and Simpson agree.
python · try it yourself
import math
import numpy as np
import matplotlib.pyplot as plt

def derivative(f, x, h=1e-5):
    h = h * max(1.0, abs(x))                     # relative step
    return (f(x + h) - f(x - h)) / (2 * h)

def gradient(f, x, h=1e-5):
    x = np.asarray(x, dtype=float)
    g = np.zeros_like(x)
    for i in range(x.size):
        e = np.zeros_like(x)
        e[i] = h * max(1.0, abs(x[i]))
        g[i] = (f(x + e) - f(x - e)) / (2 * e[i])
    return g

def simpson_samples(ys, h):
    ys = np.asarray(ys, dtype=float)             # an odd number of equally spaced samples
    return h / 3 * (ys[0] + ys[-1] + 4 * ys[1:-1:2].sum() + 2 * ys[2:-1:2].sum())

def rk4_step(f, t, y, h):
    k1 = f(t, y)
    k2 = f(t + h / 2, y + h / 2 * k1)
    k3 = f(t + h / 2, y + h / 2 * k2)
    k4 = f(t + h, y + h * k3)
    return y + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def rk4(f, y0, t0, h, n_steps, stop=None):
    t, y = t0, np.asarray(y0, dtype=float)
    ts, ys = [t], [y]
    for _ in range(n_steps):
        y = rk4_step(f, t, y, h)
        t += h
        ts.append(t)
        ys.append(y)
        if stop is not None and stop(y):
            break
    return np.array(ts), np.array(ys)

def minimize(f, x0, step0=1.0, tol=1e-6, max_iter=200):
    x = np.asarray(x0, dtype=float)
    for it in range(1, max_iter + 1):
        g = gradient(f, x)
        if np.linalg.norm(g) < tol:
            break
        fx, step = f(x), step0
        while f(x - step * g) > fx - 1e-4 * step * (g @ g):   # Armijo condition
            step /= 2
        x = x - step * g
    return x, it

G, M, K, V0, TARGET = 9.81, 0.45, 0.0057, 30.0, 40.0
def ball(t, s):
    x, y, vx, vy = s
    speed = math.hypot(vx, vy)
    return np.array([vx, vy, -K / M * speed * vx, -G - K / M * speed * vy])

def fly(angle_deg, h=0.01):
    a = math.radians(angle_deg)
    ts, ys = rk4(ball, [0.0, 0.0, V0 * math.cos(a), V0 * math.sin(a)], 0.0, h, 100_000,
                 stop=lambda s: s[1] < 0)
    lo, hi = 0.0, h                                  # bisect the last step for y = 0
    for _ in range(40):
        mid = (lo + hi) / 2
        if rk4_step(ball, ts[-2], ys[-2], mid)[1] > 0:
            lo = mid
        else:
            hi = mid
    return ts, ys, rk4_step(ball, ts[-2], ys[-2], lo), ts[-2] + lo

distance = lambda th: fly(float(th[0]))[2][0]
plt.figure(figsize=(6, 4))
for start in [20.0, 60.0]:
    th, it = minimize(lambda th: (distance(th) - TARGET)**2, [start])
    ts, ys, land, T = fly(float(th[0]))
    print(f"start {start:.0f} deg -> angle {th[0]:.4f} deg ({it} iterations), lands at {land[0]:.6f} m after {T:.3f} s")
    plt.plot(ys[:-1, 0], ys[:-1, 1], label=f"{th[0]:.2f}°")

best, it = minimize(lambda th: -distance(th), [45.0], step0=32.0)
print(f"maximum range {distance(best):.3f} m at {best[0]:.3f} deg  (no drag: {V0**2 / G:.3f} m at 45 deg)")

ts, ys, land, T = fly(float(th[0]))
n = len(ts) - 2 if (len(ts) - 2) % 2 == 0 else len(ts) - 3     # an even number of steps
speed = np.hypot(ys[:n + 1, 2], ys[:n + 1, 3])
work = simpson_samples(K * speed**3, ts[1] - ts[0])
energy = lambda s: 0.5 * M * (s[2]**2 + s[3]**2) + M * G * s[1]
print(f"lob: energy lost {energy(ys[0]) - energy(ys[n]):.6f} J,  drag work by Simpson {work:.6f} J")
plt.plot([TARGET], [0], "kx", ms=10); plt.xlabel("x (m)"); plt.ylabel("height (m)"); plt.legend()
start 20 deg -> angle 19.7724 deg (14 iterations), lands at 40.000000 m after 1.858 s
start 60 deg -> angle 62.8052 deg (7 iterations), lands at 40.000000 m after 4.458 s
maximum range 51.436 m at 40.546 deg  (no drag: 91.743 m at 45 deg)
lob: energy lost 115.659517 J,  drag work by Simpson 115.659517 J

Reading the output:

  • The flat shot at about 19.77° reaches the target after 1.86 s, and the lob at about 62.81° after 4.46 s. Both land at 40.000000 m: the remaining miss is below a micrometre.
  • With drag the best angle is about 40.5°, not 45°, and the longest kick is 51.4 m, only 56 % of the 91.7 m the drag-free formula promises. Air resistance hurts most at the top of a long, slow arc, so flatter shots pay off.
  • The lob's energy check agrees to all six printed decimals: of the initial 202.5 J of kinetic energy (12⋅0.45⋅302\frac{1}{2} \cdot 0.45 \cdot 30^2), about 115.66 J has gone into the air by the last step before landing. Two independent pieces of the toolkit, RK4 for the motion and Simpson for the power integral, give the same number.

Ideas to extend it

  • Wind. Replace vv by v−wv - w (the velocity relative to the air) in the drag term and aim into a crosswind in 3D, with two unknowns (elevation and heading) for minimize.
  • Hit a moving target. Minimise the squared distance between the ball and a target moving along a known path, over both angle and launch time.
  • Adaptive steps. Compare RK4 with step hh and two steps of h/2h/2 to estimate the local error and adjust hh automatically, as solve_ivp does.
  • Newton instead of gradient descent. Use derivative twice to get range′(θ)\text{range}'(\theta) and range′′(θ)\text{range}''(\theta), and apply Newton's method to range′(θ)=0\text{range}'(\theta) = 0 for the maximum range: it should take only a handful of iterations.
  • Spin. Add a Magnus force proportional to ω×v\omega \times v and watch the curve bend.

Test yourself

Why does derivative scale the step hh by max⁡(1,∣x∣)\max(1, \lvert x \rvert)?

  1. To make the code faster
  2. So the step stays relative to the size of xx, keeping the balance between truncation and rounding error at any scale
  3. Because the central difference needs an integer step
  4. To avoid negative steps

Doubling nn in composite Simpson divided the error by about 16. What does that confirm?

  1. The method is O(h4)O(h^4)
  2. The method is O(h2)O(h^2)
  3. The method is exact
  4. The integrand is a cubic

Why does the targeting problem have two solutions, a flat shot and a lob?

  1. Because RK4 is inaccurate
  2. Because gradient descent finds random minima
  3. Because the range first increases and then decreases with the angle, so every distance below the maximum is reached at two angles
  4. Because of the energy check