library(tidyverse)10 Simulating Motion
Most of mechanics is one sentence: find the force, divide by the mass, and you know how the velocity is changing. For a handful of forces you can turn that sentence into a formula for \(x(t)\) with pencil and paper. For everything else you let a computer take many small steps, as the falling ball in Chapter 4 did. This chapter checks that idea on a problem with a known answer, then uses it on one without.
10.1 State, time step, update
At any instant, a mass moving along a line is described by two numbers: its position \(x\) and its velocity \(v\). Together they are its state. Newton’s second law says how the state changes:
\[ \frac{dx}{dt} = v, \qquad \frac{dv}{dt} = a = \frac{F}{m}. \]
Pick a small time step \(\Delta t\) and pretend \(v\) and \(a\) are constant for that long. Then the state a moment later is
\[ x_{\text{new}} = x + v\,\Delta t, \qquad v_{\text{new}} = v + a\,\Delta t. \]
This is Euler’s method, the Euler step of Chapter 4 applied to position as well as velocity. Everything else in this chapter is a variation on those two lines.
10.2 Euler’s method on a spring
The test case is a mass on a spring, where \(F = -kx\) and so \(a = -(k/m)\,x\). Released from rest at \(x_0\), the exact motion is \(x(t) = x_0 \cos(\omega t)\) with \(\omega = \sqrt{k/m}\), which gives us something to check against.
mass_kg <- 0.5
k_n_m <- 2 # spring constant, N/m
x0_m <- 0.1 # pulled 10 cm and released from rest
omega_rad_s <- sqrt(k_n_m / mass_kg)
2 * pi / omega_rad_s
#> [1] 3.141593The period is about 3.14 s. Now the loop. Create the full-length vectors first, set their first elements to the starting state, and fill in the rest one step at a time.
dt_s <- 0.02
t_max_s <- 20
n_steps <- round(t_max_s / dt_s)
time_s <- seq(0, t_max_s, by = dt_s)
x_m <- numeric(n_steps + 1)
v_m_s <- numeric(n_steps + 1)
x_m[1] <- x0_m
for (i in 1:n_steps) {
a_m_s2 <- -k_n_m / mass_kg * x_m[i]
x_m[i + 1] <- x_m[i] + v_m_s[i] * dt_s
v_m_s[i + 1] <- v_m_s[i] + a_m_s2 * dt_s
}Element i holds the state now, element i + 1 the state one step later. v_m_s[1] is already zero, which is what released from rest means. Put the results in a tibble, with the exact solution alongside:
euler <- tibble(
time_s = time_s,
x_m = x_m,
v_m_s = v_m_s,
exact_m = x0_m * cos(omega_rad_s * time_s)
)
ggplot(euler, aes(time_s)) +
geom_line(aes(y = exact_m), linetype = "dashed") +
geom_line(aes(y = x_m), color = "firebrick") +
labs(x = "Time (s)", y = "Position (m)")
The dashed curve is the cosine. Euler’s method (red) gets the timing about right, but its swings keep getting bigger. A real spring does not do that.
max(abs(euler$x_m))
#> [1] 0.2125053The mass started 0.1 m from equilibrium and has reached more than twice that. Each step overshoots slightly, always outward, and a thousand overshoots compound.
10.3 Two lines swapped: Euler-Cromer
The fix costs nothing. Update the velocity first, then use the new velocity to update the position:
x_m[1] <- x0_m
v_m_s[1] <- 0
for (i in 1:n_steps) {
a_m_s2 <- -k_n_m / mass_kg * x_m[i]
v_m_s[i + 1] <- v_m_s[i] + a_m_s2 * dt_s
x_m[i + 1] <- x_m[i] + v_m_s[i + 1] * dt_s # new velocity
}
cromer <- tibble(time_s = time_s, x_m = x_m, v_m_s = v_m_s)
max(abs(cromer$x_m))
#> [1] 0.1000199This is the Euler-Cromer method, and the amplitude stays at 0.1 m. The clearest way to see the difference is through the total energy, \(E = \tfrac12 m v^2 + \tfrac12 k x^2\), which the real system conserves. Stack the two tibbles with bind_rows(), a dplyr function that puts one table under another. Its .id argument adds a column, here called method, recording which table each row came from. Then compute the energy for both at once.
both <- bind_rows(euler = euler, cromer = cromer, .id = "method") |>
mutate(energy_j = 0.5 * mass_kg * v_m_s^2 + 0.5 * k_n_m * x_m^2)
ggplot(both, aes(time_s, energy_j, color = method)) +
geom_line() +
labs(x = "Time (s)", y = "Total energy (J)", color = "Method")
both |>
summarise(start_j = first(energy_j), end_j = last(energy_j),
min_j = min(energy_j), max_j = max(energy_j),
.by = method)
#> # A tibble: 2 × 5
#> method start_j end_j min_j max_j
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 euler 0.01 0.0495 0.01 0.0495
#> 2 cromer 0.01 0.0102 0.00980 0.0102first() and last() pick out the first and last value in each group. Both methods start with 0.01 J. Euler ends with nearly five times that, energy created by arithmetic. Euler-Cromer’s energy is not exactly constant either: it wobbles by about two percent, twice per oscillation. But it wobbles around the right value and never drifts away. For anything that oscillates or orbits, that matters more than accuracy on any single step.
10.4 An integrator in a function
Copying a loop and editing it is how mistakes get made. Wrap it in a function that returns a tibble.
simulate_oscillator <- function(x0, v0, k, m, dt, t_max,
method = "euler-cromer") {
n <- round(t_max / dt)
x <- numeric(n + 1)
v <- numeric(n + 1)
x[1] <- x0
v[1] <- v0
for (i in 1:n) {
a <- -k / m * x[i]
v[i + 1] <- v[i] + a * dt
if (method == "euler") {
x[i + 1] <- x[i] + v[i] * dt
} else {
x[i + 1] <- x[i] + v[i + 1] * dt
}
}
tibble(
time_s = dt * (0:n),
x_m = x,
v_m_s = v,
energy_j = 0.5 * m * v^2 + 0.5 * k * x^2
)
}Now an experiment is one line. Try a smaller time step for Euler’s method. slice_tail(n = 1) keeps only the last row of a table, here the state at the end of the run.
simulate_oscillator(0.1, 0, k = 2, m = 0.5, dt = 0.02, t_max = 20,
method = "euler") |>
slice_tail(n = 1)
#> # A tibble: 1 × 4
#> time_s x_m v_m_s energy_j
#> <dbl> <dbl> <dbl> <dbl>
#> 1 20 -0.145 -0.338 0.0495
simulate_oscillator(0.1, 0, k = 2, m = 0.5, dt = 0.01, t_max = 20,
method = "euler") |>
slice_tail(n = 1)
#> # A tibble: 1 × 4
#> time_s x_m v_m_s energy_j
#> <dbl> <dbl> <dbl> <dbl>
#> 1 20 -0.0989 -0.223 0.0223Halving the step doubles the work and brings the final energy from 0.0495 J down to 0.0223 J, still more than twice the true 0.01 J. Smaller steps slow Euler’s drift but never stop it. Euler-Cromer at the original, coarser step does better for half the cost:
simulate_oscillator(0.1, 0, k = 2, m = 0.5, dt = 0.02, t_max = 20) |>
slice_tail(n = 1)
#> # A tibble: 1 × 4
#> time_s x_m v_m_s energy_j
#> <dbl> <dbl> <dbl> <dbl>
#> 1 20 -0.0684 -0.149 0.010210.5 A pendulum with no formula
The textbook pendulum period, \(T = 2\pi\sqrt{L/g}\), comes from replacing \(\sin\theta\) with \(\theta\), which is only good for small swings. The honest equation is
\[ \frac{d^2\theta}{dt^2} = -\frac{g}{L}\sin\theta , \]
and it has no solution in terms of functions you know. The loop does not care. The state is now the angle \(\theta\) and the angular velocity \(d\theta/dt\), and the only line that changes is the acceleration. Release a 1 m pendulum from rest at 90 degrees, with the string horizontal, and follow it for 5 s with a smaller step than before:
g_m_s2 <- 9.81
length_m <- 1
dt_s <- 0.001
n_steps <- 5000 # 5 s
theta_rad <- numeric(n_steps + 1)
ang_vel_rad_s <- numeric(n_steps + 1)
theta_rad[1] <- pi / 2
for (i in 1:n_steps) {
alpha_rad_s2 <- -g_m_s2 / length_m * sin(theta_rad[i])
ang_vel_rad_s[i + 1] <- ang_vel_rad_s[i] + alpha_rad_s2 * dt_s
theta_rad[i + 1] <- theta_rad[i] + ang_vel_rad_s[i + 1] * dt_s
}
swing <- tibble(time_s = dt_s * (0:n_steps), theta_rad = theta_rad)
ggplot(swing, aes(time_s, theta_rad * 180 / pi)) +
geom_line() +
labs(x = "Time (s)", y = "Angle (degrees)")
It looks like a cosine with slightly flattened peaks: the pendulum lingers near the top of its swing, because the restoring pull grows as \(\sin\theta\), more slowly than the \(\theta\) the small-angle formula assumes. To measure the period, use the symmetry of the motion. The pendulum reaches the bottom, \(\theta = 0\), after exactly a quarter of a period, so find the first row where the angle has gone negative and multiply its time by four. slice_head(n = 1) is the partner of slice_tail(): it keeps the first row.
first_crossing <- swing |>
filter(theta_rad < 0) |>
slice_head(n = 1)
period_sim_s <- 4 * first_crossing$time_s
period_small_s <- 2 * pi * sqrt(length_m / g_m_s2)
c(simulated = period_sim_s, small_angle = period_small_s)
#> simulated small_angle
#> 2.368000 2.006067
period_sim_s / period_small_s
#> [1] 1.180419The simulated period is 2.368 s against the small-angle formula’s 2.006 s, 18% longer. The formula is wrong for that swing, and twenty lines of R told you by how much.
10.6 Bigger states
Nothing here was specific to springs or pendulums. A projectile with air resistance has a state of four numbers (\(x\), \(y\), \(v_x\), \(v_y\)) and a different line for the acceleration. Three stars pulling on each other have eighteen. It is still the same loop: compute accelerations from the current state, update velocities, update positions, repeat.
For gravity between several bodies, the method of choice is a close relative of Euler-Cromer called velocity Verlet, which keeps the bounded energy and is more accurate for the same step. You do not have to write it: Chapter 11 introduces a package that does it for you and hands back a tibble.