---
title: Motion lab
heading: Velocity from position data, planned moves, and drag solutions checked by simulation
eyebrow: B1 · Lesson 13 · Motion lab
xp: 50
---

::: hook
Real motion arrives as data. An encoder on a motor shaft or a GPS receiver reports position at regular ticks, and velocity and acceleration have to be computed from it. A motion controller works the other way: it plans a move from a distance, an acceleration limit and a top speed. And the exact drag solutions of lesson 8 are only worth trusting once a simulation agrees with them. In this lab you'll write all three: differentiating data, planning moves, and integrating motion with drag.
:::

::: play
- A motion controller moves a stage a distance d with acceleration a and a top speed limit. The curve is the planned speed against time: speed up, cruise, slow down.
- Shorten the move, or lower the acceleration: below $d = v_\text{max}^2/a$ the stage never reaches top speed and the profile becomes a triangle.
- The readouts give the move time and the peak speed. You'll write the same calculation in step 2.
:::

```sim plot
view: graph
x: t = 0..20 s
y: v = 0..5 m/s
slider: d = 1..40 step 0.5 = 30 m
slider: a = 0.5..4 step 0.1 = 1 m/s²
slider: vm = 0.5..5 step 0.1 = 2.5 m/s
plot: a*t*step((vm - (vm - sqrt(a*d))*step(vm^2/a - d))/a - t) + (vm - (vm - sqrt(a*d))*step(vm^2/a - d))*step(t - (vm - (vm - sqrt(a*d))*step(vm^2/a - d))/a)*step(d/(vm - (vm - sqrt(a*d))*step(vm^2/a - d)) - t) + a*(d/(vm - (vm - sqrt(a*d))*step(vm^2/a - d)) + (vm - (vm - sqrt(a*d))*step(vm^2/a - d))/a - t)*step(t - d/(vm - (vm - sqrt(a*d))*step(vm^2/a - d)))*step(d/(vm - (vm - sqrt(a*d))*step(vm^2/a - d)) + (vm - (vm - sqrt(a*d))*step(vm^2/a - d))/a - t) | label: planned speed | samples: 800
readout: move time, s = d/(vm - (vm - sqrt(a*d))*step(vm^2/a - d)) + (vm - (vm - sqrt(a*d))*step(vm^2/a - d))/a | digits: 4
readout: peak speed, m per s = (vm - (vm - sqrt(a*d))*step(vm^2/a - d)) | digits: 3
```

::: predict
## A stage must move 3 m with 1 m/s² of acceleration and a 2.5 m/s speed limit. Does it reach 2.5 m/s?

- [ ] Yes, and it cruises for most of the move
- [ ] Yes, for an instant at the middle
- [x] No: it peaks at 1.73 m/s and the move takes 3.46 s
- [ ] It can't make the move at all

::: reveal
No. Reaching 2.5 m/s and stopping again takes $v_\text{max}^2/a = 6.25$ m, more than the 3 m available. So the stage accelerates for half the distance and brakes for the other half, peaking at $\sqrt{ad} = 1.73$ m/s, and the move takes $2\sqrt{d/a} = 3.46$ s.
:::
:::

::: nameit
## Derivatives from samples

For positions $x_i$ sampled every h seconds, the **central differences**

$$v_i \approx \frac{x_{i+1} - x_{i-1}}{2h}, \qquad a_i \approx \frac{x_{i+1} - 2x_i + x_{i-1}}{h^2}$$

are accurate to order $h^2$: the velocity's error is about $\frac{h^2}{6}\dddot x$. They need a point on each side, so the first and last samples get no estimate. Noise is the catch: each difference divides by h or $h^2$, so a millimeter of noise sampled every millisecond becomes meters per second of velocity noise, and real controllers filter before or after differentiating.

## Trapezoidal moves

With acceleration a and speed limit $v_\text{max}$, a move of length d takes

$$T = \frac{d}{v_\text{max}} + \frac{v_\text{max}}{a} \quad (d \ge v_\text{max}^2/a), \qquad T = 2\sqrt{\frac da} \quad (\text{otherwise}).$$

## Range from a height

Launched at speed $v_0$ and angle θ from height h, a projectile lands at $R = \frac{v_0\cos\theta}{g}\left(v_0\sin\theta + \sqrt{v_0^2\sin^2\theta + 2gh}\right)$. The best angle is $\tan^{-1}\frac{v_0}{\sqrt{v_0^2 + 2gh}}$, a little under 45°.

## Checking a stepping method

Euler's method on $\dot v = g - v/\tau$ gives $v_n = g\tau\left(1 - (1 - h/\tau)^n\right)$ exactly, so its error can be predicted as well as measured. Halving the step halves Euler's error and divides RK4's by 16, which is how you tell which method you've actually written.
:::

::: example
## Positions $x = 3t^2 - t^3$ are sampled every 0.1 s. What do central differences give for the velocity and acceleration at t = 1 s?

::: solution
1. **Exact values.**
   $$\begin{aligned} v &= 6t - 3t^2 \\ &= 3\ \text{m/s} \\ a &= 6 - 6t \\ &= 0 \end{aligned}$$
2. **The samples.**
   $$\begin{aligned} x(0.9) &= 1.701 \\ x(1) &= 2 \\ x(1.1) &= 2.299 \end{aligned}$$
3. **Central differences.**
   $$\begin{aligned} v &\approx \frac{2.299 - 1.701}{0.2} \\ &= 2.99\ \text{m/s} \\ a &\approx \frac{2.299 - 4 + 1.701}{0.01} \\ &= 0 \end{aligned}$$
4. **The errors.** The velocity is off by exactly
   $$\begin{aligned} \frac{h^2}{6}\dddot x &= \frac{0.01}{6} \times (-6) \\ &= -0.01\ \text{m/s} \end{aligned}$$
   The second difference is exact for a cubic, since its error depends on the fourth derivative.

**Answer:** the central differences give 2.99 m/s (exact value 3 m/s) and an acceleration of 0, which is exact.
:::
:::

::: example
## How long does a 30 m move take with 1 m/s² of acceleration and a 2.5 m/s limit?

::: solution
1. **Ramps.** Reaching 2.5 m/s takes 2.5 s and covers 3.125 m; braking takes the same.
2. **Cruise.** That leaves 23.75 m of cruising, 9.5 s at 2.5 m/s.
3. **Total.**
   $$2.5 + 9.5 + 2.5 = 14.5\ \text{s}$$
   which matches $\frac{30}{2.5} + \frac{2.5}{1}$.
4. **What limits it.** Doubling the acceleration saves only 1.25 s here, while raising the speed limit to 5 m/s saves 3.5 s: long moves are limited by speed, short ones by acceleration.

**Answer:** the move takes 14.5 s.
:::
:::

::: example
## A stone is thrown at 15 m/s from the top of a 10 m cliff. What angle throws it farthest, and how far?

::: solution
1. **Best angle.**
   $$\begin{aligned} \theta &= \tan^{-1}\frac{15}{\sqrt{225 + 2 \times 9.8 \times 10}} \\ &= \tan^{-1}\frac{15}{20.52} \\ &= 36.2° \end{aligned}$$
2. **Range at that angle.**
   $$\begin{aligned} R &= \frac{v_0\sqrt{v_0^2 + 2gh}}{g} \\ &= \frac{15 \times 20.52}{9.8} \\ &= 31.4\ \text{m} \end{aligned}$$
3. **Compare with 45°.** At 45° it would land at 30.5 m. The higher the launch compared with $\frac{v_0^2}{g}$, the flatter the best throw, since the long fall already provides the flight time.

**Answer:** throw at 36.2° above horizontal; the stone goes 31.4 m.
:::
:::

::: check
kind: python

## Step 1. Write `derivatives(t, x)` that returns two NumPy arrays: the central-difference velocity and acceleration at the interior samples (all but the first and last). The samples are evenly spaced.

```python starter
import numpy as np

def derivatives(t, x):
    v = np.zeros(len(t) - 2)
    a = np.zeros(len(t) - 2)
    return v, a

t = np.linspace(0, 2, 21)
v, a = derivatives(t, 3 * t**2 - t**3)
print(v[9], a[9])
```

```python solution
import numpy as np

def derivatives(t, x):
    h = t[1] - t[0]
    v = (x[2:] - x[:-2]) / (2 * h)
    a = (x[2:] - 2 * x[1:-1] + x[:-2]) / h**2
    return v, a

t = np.linspace(0, 2, 21)
v, a = derivatives(t, 3 * t**2 - t**3)
print(v[9], a[9])
```

```python tests
import numpy as np
t = np.linspace(0, 2, 21)
v, a = derivatives(t, 3 * t**2 - t**3)
assert len(v) == 19 and len(a) == 19, f"Expect 19 interior estimates from 21 samples; got {len(v)} and {len(a)}."
assert abs(v[9] - 2.99) < 1e-9, f"At t = 1 the central difference should give 2.99 m/s (exact 3, error -h²/6 × 6); got {v[9]}."
assert abs(v[4] - 2.24) < 1e-9, f"At t = 0.5 it should give 2.24 m/s; got {v[4]}."
assert abs(a[9]) < 1e-9 and abs(a[4] - 3) < 1e-9, f"The second difference is exact for a cubic: 0 at t = 1 and 3 at t = 0.5; got {a[9]} and {a[4]}."
t2 = np.linspace(0, 1, 11)
v2, a2 = derivatives(t2, 5 * t2)
assert np.allclose(v2, 5) and np.allclose(a2, 0, atol=1e-9), "Steady motion at 5 m/s should give v = 5 and a = 0 everywhere."
```

::: right
Right. Each estimate uses the samples on both sides, which cancels the leading error term.
:::
:::

::: check
kind: python

## Step 2. Write `move_time(d, a, vmax)` that returns the time of a trapezoidal move of length `d`, or of a triangular one when the stage can't reach `vmax`.

```python starter
import math

def move_time(d, a, vmax):
    return d / vmax

print(move_time(30, 1, 2.5), move_time(3, 1, 2.5))
```

```python solution
import math

def move_time(d, a, vmax):
    if d >= vmax**2 / a:
        return d / vmax + vmax / a
    return 2 * math.sqrt(d / a)

print(move_time(30, 1, 2.5), move_time(3, 1, 2.5))
```

```python tests
import math
assert abs(move_time(30, 1, 2.5) - 14.5) < 1e-9, f"30 m at 1 m/s² with a 2.5 m/s limit takes 14.5 s; got {move_time(30, 1, 2.5)}."
assert abs(move_time(3, 1, 2.5) - 2 * math.sqrt(3)) < 1e-9, f"3 m never reaches 2.5 m/s: 2√(d/a) = 3.464 s; got {move_time(3, 1, 2.5)}."
assert abs(move_time(6.25, 1, 2.5) - 5.0) < 1e-9, "At d = vmax²/a both formulas give 5 s."
assert abs(move_time(1, 4, 10) - 1.0) < 1e-9, f"1 m at 4 m/s² with a high limit takes 1 s; got {move_time(1, 4, 10)}."
```

::: right
Right. The two formulas meet at $d = v_\text{max}^2/a$, where the cruise shrinks to nothing.
:::
:::

::: check
kind: python

## Step 3. Write `range_from_height(v0, theta, h)` (theta in degrees, g = 9.8) and `best_angle(v0, h)`, which searches angles from 20° to 60° in steps of 0.1° and returns the one with the longest range.

```python starter
import numpy as np
import math
g = 9.8

def range_from_height(v0, theta, h):
    return v0**2 * math.sin(2 * math.radians(theta)) / g

def best_angle(v0, h):
    return 45.0

print(range_from_height(20, 45, 1.5), best_angle(20, 1.5))
```

```python solution
import numpy as np
import math
g = 9.8

def range_from_height(v0, theta, h):
    th = math.radians(theta)
    vx, vy = v0 * math.cos(th), v0 * math.sin(th)
    return vx * (vy + math.sqrt(vy**2 + 2 * g * h)) / g

def best_angle(v0, h):
    angles = np.arange(20, 60.0001, 0.1)
    ranges = [range_from_height(v0, a, h) for a in angles]
    return angles[int(np.argmax(ranges))]

print(range_from_height(20, 45, 1.5), best_angle(20, 1.5))
```

```python tests
import math
assert abs(range_from_height(20, 45, 0) - 400 / 9.8) < 1e-9, "From the ground the range is v0² sin 2θ / g = 40.82 m."
r = range_from_height(20, 30, 10)
assert abs(r - 48.0815) < 1e-3, f"From 10 m at 30° the ball lands 48.08 m away; got {r:.4f}."
b = best_angle(20, 1.5)
assert abs(b - 43.98) < 0.11, f"From 1.5 m at 20 m/s the best angle is about 43.98°; got {b}."
assert abs(best_angle(20, 0) - 45) < 0.11, "From the ground the best angle is 45°."
assert best_angle(10, 20) < 30, "From a 20 m cliff at 10 m/s the best angle is well under 30°."
```

::: right
Right. Your search reproduces lesson 3's 44.0° for a throw from 1.5 m, and from a 20 m cliff at 10 m/s it finds 24.3°.
:::
:::

::: check
kind: python

## Step 4. Write `euler_fall(tau, T, n)` that takes n Euler steps of $\dot v = g - v/\tau$ from rest up to time T and returns v. (Use g = 9.8.)

```python starter
import math
g = 9.8

def euler_fall(tau, T, n):
    return g * tau * (1 - math.exp(-T / tau))

print(euler_fall(0.5, 1, 1000))
```

```python solution
import math
g = 9.8

def euler_fall(tau, T, n):
    h = T / n
    v = 0.0
    for _ in range(n):
        v += h * (g - v / tau)
    return v

print(euler_fall(0.5, 1, 1000))
```

```python tests
import math
exact = 9.8 * 0.5 * (1 - math.exp(-2))
for n in (10, 1000):
    pred = 9.8 * 0.5 * (1 - (1 - 1 / n / 0.5)**n)
    got = euler_fall(0.5, 1, n)
    assert abs(got - pred) < 1e-9, f"With {n} steps Euler gives gτ(1 - (1 - h/τ)^n) = {pred:.10f}; got {got}."
e1 = abs(euler_fall(0.5, 1, 1000) - exact)
e2 = abs(euler_fall(0.5, 1, 2000) - exact)
assert 1.9 < e1 / e2 < 2.1, f"Halving Euler's step should halve its error; the ratio was {e1 / e2:.3f}."
```

::: right
Right. With 1000 steps Euler lands 1.3 mm/s above the exact 4.2369 m/s, and halving the step halves that.
:::
:::

::: check
kind: python

## Step 5. Write `fall(vt, T, dt)` that integrates a fall from rest with quadratic drag, $\dot v = g(1 - v^2/v_t^2)$ and $\dot x = v$, by RK4, and returns `(v, x)` at time T. Check it against lesson 8's exact formulas.

```python starter
import numpy as np
g = 9.8

def fall(vt, T, dt):
    return g * T, 0.5 * g * T**2

print(fall(50, 7.5113, 0.0075113))
```

```python solution
import numpy as np
g = 9.8

def fall(vt, T, dt):
    def f(s):
        return np.array([s[1], g * (1 - s[1]**2 / vt**2)])
    s = np.array([0.0, 0.0])
    for _ in range(int(round(T / dt))):
        k1 = f(s)
        k2 = f(s + dt / 2 * k1)
        k3 = f(s + dt / 2 * k2)
        k4 = f(s + dt * k3)
        s = s + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
    return s[1], s[0]

print(fall(50, 7.5113, 0.0075113))
```

```python tests
import math
T = 50 / 9.8 * math.atanh(0.9)
v, x = fall(50, T, T / 1000)
assert abs(v - 45) < 1e-6, f"After {T:.4f} s the speed should be 0.9 × 50 = 45 m/s; got {v}."
assert abs(x - 2500 / 9.8 * math.log(math.cosh(9.8 * T / 50))) < 1e-4, f"The distance should be (vt²/g) ln cosh(gT/vt) = 211.83 m; got {x}."
v2, x2 = fall(30, 4, 0.001)
assert abs(v2 - 30 * math.tanh(9.8 * 4 / 30)) < 1e-6 and abs(x2 - 62.8391) < 1e-3, f"For vt = 30 after 4 s: 25.903 m/s and 62.839 m; got {v2:.4f} and {x2:.4f}."
```

::: right
Right. The simulation and the tanh formula agree to many digits, so each confirms the other.
:::
:::

::: check
kind: parts
given: d = 1 | 2 | 3; a = 1 | 2; vm = 4 | 5

## A stage moves {d} m with {a} m/s² of acceleration and a {vm} m/s limit.

::: part
answer: sqrt(a*d)
unit: m/s
tolerance: 0.5%

### What peak speed does it reach?

::: misses
- [vm] It can't reach the limit: $v_\text{max}^2/a$ is longer than the move.
- [any] Half the distance accelerating: $v^2 = 2a\frac d2$.
:::
:::

::: part
answer: 2*sqrt(d/a)
unit: s
tolerance: 0.5%

### How long does the move take?

::: misses
- [d/vm + vm/a] That's the trapezoidal formula; this move is triangular.
- [any] $2\sqrt{d/a}$.
:::
:::
:::

::: check
given: h = 0.01 | 0.02 | 0.05; j = 6 | 12
answer: h^2/6*j
unit: m/s
tolerance: 0.5%

## Position samples are spaced {h} s apart, and the motion has a constant third derivative (jerk) of {j} m/s³. How large is the central-difference velocity's error?

::: right
Right. $\frac{h^2}{6}\dddot x$: halving the spacing quarters the error.
:::

::: misses
- [h*j/2] That's a one-sided difference's error order; the central one is second order.
- [any] $\frac{h^2}{6}\dddot x$.
:::
:::

::: explain
## Why is a central difference more accurate than a forward difference for the same sample spacing?

::: model
A forward difference, $(x_{i+1} - x_i)/h$, really measures the average velocity over the next interval, which is the velocity half a step later than the point it's assigned to, so its error is proportional to h times the acceleration. A central difference spans one step on each side, so the effects of acceleration on the two sides cancel by symmetry: the leading error term drops out, and what's left is proportional to $h^2$ times the third derivative. Halving the spacing therefore halves a forward difference's error but quarters a central one's.
:::
:::

::: practice

::: check
given: d = 10 | 50; a = 0.5 | 2; vm = 1 | 2
answer: d/vm + vm/a
unit: s
tolerance: 0.5%

## Move time for {d} m at {a} m/s² with a {vm} m/s limit?

::: misses
- [any] $\frac{d}{v_\text{max}} + \frac{v_\text{max}}{a}$, since the move is long enough to cruise.
:::
:::

::: check
given: v = 10 | 25; h = 2 | 10
answer: atan(v/sqrt(v^2 + 2*9.8*h))*180/pi
unit: °
tolerance: 0.5%

## Best launch angle at {v} m/s from {h} m?

::: misses
- [any] $\tan^{-1}\frac{v_0}{\sqrt{v_0^2 + 2gh}}$.
:::
:::
:::
