Notes
1P1 Mechanics · Topic 5

Numerical integration

Lecture 5 · Mon 26 Oct

Section 5: Introduction to numerical integration

If an equation of motion cannot be solved analytically, it can be solved numerically. Numerical solutions approximate the equation of motion by discretisation.

Definition Discretisation

Dividing the continuous time evolution of a system into small but discrete time steps . The equation of motion is then approximated by relations between the state at successive instants .

There are two main steps for systems of particles or rigid bodies:

  1. Approximate the derivatives in the equation of motion using discrete time steps.
  2. Solve the discrete equation at every time step to build up the answer.

Discretisation introduces numerical errors. Always check that they are not so big that the answer is meaningless.

This course covers two simple methods: Euler’s method and the Euler–Cromer (semi-implicit) method. Each one is applied time step by time step, starting from the Initial conditions.

Explanation Why is this called ‘integration’?

Solving for means integrating twice: once for , then again for . For a simple you can do this on paper (as for Car stopping: time and distance). A numerical method does the same integration in small pieces, so it works for any you can evaluate.

  • Numerical integration: chop time into steps , approximate the derivatives, and march the equation of motion forward from the initial conditions.
  • Every numerical answer carries a discretisation error. Always check it.

Euler’s method

Euler’s method rests on the Taylor series (Mathematics Databook):

Euler’s method keeps only the first two terms of this series and discards the rest.

Equation First-order (Euler) step memorise

Starting from , follow the tangent (slope ) for a time .

Show derivation

Take the Taylor series (Mathematics Databook; Taylor series) with , , :

By definition (Velocity and acceleration). Truncate after the first-order term. The neglected remainder is , which is small when is small.

Geometrically, the estimate lands on the tangent at , not on the curve. The handout calls this the “first-order approximation”. The gap between tangent and curve grows like .

Interactive figure

Shrink and the orange estimate closes onto the true curve: halving roughly quarters the one-step error. Move to where the curve bends most and the error is largest.

Figure Euler step: following the tangent
Explanation Isn’t this just numerical differentiation run backwards?

Yes. Rearranged, the Euler step reads . That is the Single-sided estimate estimate of the derivative from Section 3. The forward difference is only first-order accurate, and Euler’s method inherits that accuracy.

  • Euler step = first two Taylor terms: , i.e. follow the tangent.
  • Error per step : small steps, small error.

Euler’s method works as follows

Divide time into discrete intervals and consider the th interval, from to :

t = 0 Δt 2Δt 3Δt (n−1)Δt nΔt step n t

Subscripts label the instants: , and likewise , , .

Figure Time divided into steps Δt
Equation Euler’s method memorise

Everything on the right comes from the previous step . is the force evaluated with , and .

Show derivation
  1. Apply Newton's second law at : .
  2. Apply the First-order (Euler) step to with and : .
  3. Apply the same step to , using (Velocity and acceleration): .

These three lines give the solution at the th time step. Repeat them for step , and so on, until you reach the intended time.

  • Each step: force → → → , using only values from step .
  • Start from the initial conditions , . Repeat until the end time.

The ‘Euler-Cromer’ (or ‘semi-implicit’) method

This works in the same way as the basic Euler method, with one change in the last line.

Equation Euler–Cromer (semi-implicit) method memorise

The position update uses the new velocity , which has just been computed.

Show derivation

The first two lines are the same as in Euler's method: Newton’s second law at , then the First-order (Euler) step for .

For , expand about the end of the interval instead. Use the Taylor series (Taylor series) with and step :

Rearranging gives . The neglected term is , the same order as in Euler’s method.

Watch out

The only difference from Euler is in the position update: , not . So the velocity must be updated before the position.

t x xn−1 tn−1 tn Euler: slope vn−1 exact x(t) Euler–Cromer: slope vn

For a decelerating body , so Euler overshoots and Euler–Cromer undershoots. Under constant deceleration the exact position lies exactly halfway between them.

Figure One step of each method (decelerating particle)
Explanation Isn’t using v_n ‘cheating’, since it’s the velocity at the end of the step?

No. has already been calculated explicitly in the line above, so nothing new has to be solved. Both choices are equally valid first-order approximations of over the step. Euler uses the left end of the interval and Euler–Cromer uses the right end. The figure above shows that, when is changing, they err in opposite directions.

  • Euler–Cromer = Euler, but with updated using the new . Compute first.
  • Same order of accuracy as Euler, but usually more stable with better energy behaviour (see the examples).

First-order methods and checking numerical accuracy

Definition First-order method

A method that uses only the first-derivative term of the Taylor series, as both Euler and Euler–Cromer do. Its error is proportional to (see Error of a first-order method). Second- and higher-order methods keep more Taylor terms. For a given time step they have a smaller error.

  • Any method is a recipe: a fixed sequence of steps computed repeatedly, i.e. an algorithm. Higher-order methods look more complicated, but they are still just algorithms. More methods appear later in the Tripos.
  • Engineers must know the issues these schemes can cause and how to check that a simulation gives reliable answers.
Result Two standard checks on a numerical solution
  1. Check a case, or aspects of the simulation, you know the answer to.
  2. Check convergence: make smaller (increase ) until the answer stops changing.
Explanation What counts as ‘a case you know the answer to’?

Look for anything you can predict without the computer:

  • a special case of the same code (switch the drag off and compare with the drag-free projectile; set );
  • a conserved quantity (no damping means energy must stay constant);
  • an equilibrium (a body started at rest in equilibrium must stay there);
  • a back-of-envelope number such as Braking distance (constant friction).

For convergence, run at , , . For a first-order method each run should change the answer by about half as much as the previous change. Stop when the change is below the accuracy you need.

  • First-order = only the first Taylor term. Higher order gives a smaller error for the same .
  • Always (1) test against something known, (2) shrink until the answer stops changing.

Example: car stopping

Return to the stopping car. Its equation of motion is (Car stopping: equation of motion):

Equation Car stopping: update rules memorise
Show derivation

Substitute from Car stopping: equation of motion into the velocity line of Euler's method (with ). The position line is the one from Euler's method or from Euler–Cromer (semi-implicit) method.

This is a procedure for computing the velocity and position at successive time steps. Here the acceleration is constant, so it does not need to be updated at each step.

Only the states (position and velocity) at past times are needed, which makes the scheme easy to solve.

Definition Explicit, implicit and semi-implicit schemes
  • Explicit (basic Euler): the next time step is calculated explicitly from the previous time steps.
  • Implicit: an equation must be solved at each time step, because the unknown new state appears on both sides.
  • Semi-implicit (Euler–Cromer): uses the current velocity , but needs no equation to be solved, because has already been computed explicitly.
Explanation What would a fully implicit step look like?

Evaluate the acceleration at the new state instead. This is called backward Euler and is beyond this course. For linear drag it gives . The unknown appears on both sides, so you solve for it: . For a nonlinear force this becomes a nonlinear equation at every step, which is why implicit schemes cost more per step.

The Python recipe

The key part of the code matches the steps above line by line (the handout labels it “recipe”):

for n in range(1,N):
    xddot[n-1] = -mu*g                        # x'' = -mu g
    xdot[n]    = xdot[n-1] + xddot[n-1] * dt
    xe[n]      = xe[n-1]   + xdot[n-1]  * dt  # EULER'S METHOD
    xs[n]      = xs[n-1]   + xdot[n]    * dt  # SEMI-IMPLICIT METHOD

Two choices have to be made before running it:

  • Total simulation time. It must be long enough to include the stop, but not so long that the run goes well past it. Alternatively, a while loop can stop automatically at the right time.
  • Number of time samples . Larger gives smaller steps but slower computation. That cost is negligible here but matters in big simulations.

Results and convergence

Define error for the stopping distance .

analytic (m) Euler (m) semi-implicit (m) Euler error semi-implicit error
10 60.407 69.508 51.731 9.101 8.676
100 60.407 61.217 59.601 0.810 0.806
  • is a really small number of steps. Euler predicts too much energy (it overshoots) and semi-implicit too little (it undershoots). Both are still within about 15%, which is not bad.
  • more steps gives a smaller error.
  • On a log–log plot of error against (handout Fig. 5.4), both methods lie on a straight line: multiplying by 10 divides the error by 10. The step size is , so error ∝ Δt.
Interactive figure

Start at (handout Fig. 5.1), then go to (Fig. 5.2). Watch the curves close in and the point slide down the slope −1 line on the right. The parameters ( m/s, , m/s², 6 s run with ) were inferred to reproduce the handout’s numbers.

Figure Car stopping: Euler vs semi-implicit as N grows
Result Error of a first-order method memorise

Halving the step halves the error. On a log–log plot of error against the slope is . Second- and higher-order methods have a smaller error for the same and converge faster as increases.

Show derivation beyond this lecture

Each step discards the Taylor term , so the error made in one step is (First-order (Euler) step). Reaching a fixed end time takes steps. If the step errors simply accumulate (rather than being amplified), the total error is about , which is proportional to and hence to .

For a th-order method the per-step error is , so the total is : slope on the log–log plot.

The car example confirms this. There the error is ; see the extra below.

This is the convergence check, and it is essential for any simulation. It does not need the analytic solution: just watch how much the result changes as increases.

  • The two methods have practically the same error here. That is expected, since both are first-order.
  • The semi-implicit scheme is often better, because it is generally more stable and has better energy-preserving properties. The full reasons are beyond the course.
  • Did this tell us more than the back-of-the-envelope Braking distance (constant friction)? Not much. It also computed far more than we wanted (the whole time history). Be clear about what you want to find before solving, and value quick hand estimates. But we can now get approximate answers when there is no straightforward analytic solution.
Explanation Why is the car’s error exactly proportional to Δt?

With constant deceleration the velocity is exact at every grid point: . The two position updates are sums of these velocities:

Because is linear in , the trapezium rule is exact, and it is the average of these two sums. So , and therefore
At the stop , so the errors are .

Check with , s, m/s: m. The handout’s 9.101 and 8.676 average to 8.89; they differ slightly because the maximum is sampled only at grid points.

Explanation Why do all the x(t) curves come back down after about 4.5 s?

The model is only valid while the car is moving forwards. The code does not know the car has stopped, so it keeps decelerating and the car “reverses”. Real friction would drop to zero at rest. The stopping distance is therefore the maximum of , which is how the handout reads it off.

  • Car: ; position by Euler () or semi-implicit ().
  • Euler overshoots (“too much energy”), semi-implicit undershoots (“too little”), each by .
  • gives smaller error: first order. Convergence can be checked without the analytic answer.
  • Explicit = from past states only; implicit = solve an equation each step; semi-implicit = uses , no equation.

Example: projectile with air resistance

Projectile motion with drag proportional to velocity (Linear drag model (assumed)) can be solved analytically (Projectile with linear drag: trajectory), but that is extremely long-winded. Numerically it is very straightforward. The code is nearly identical to the car’s. The only changes are that both and are solved for, and that the acceleration expressions differ (Projectile with linear drag: equations of motion).

Equation Projectile with drag: update rules memorise

Then update and , and then and , exactly as in Euler's method or Euler–Cromer (semi-implicit) method, applied to each component separately.

Show derivation

Projectile with linear drag: equations of motion gives and . Evaluate both at (the previous step), as the first line of Euler's method requires.

for n in range(1,N):
    xddot[n-1] = -k/m*xdot[n-1]          # x'' = -(k/m) x'
    yddot[n-1] = -g - k/m*ydot[n-1]      # y'' = -g - (k/m) y'

    xdot[n] = xdot[n-1] + xddot[n-1] * dt
    ydot[n] = ydot[n-1] + yddot[n-1] * dt

    xe[n]   = xe[n-1] + xdot[n-1] * dt   # EULER'S METHOD
    ye[n]   = ye[n-1] + ydot[n-1] * dt   # EULER'S METHOD

    xs[n]   = xs[n-1] + xdot[n]   * dt   # SEMI-IMPLICIT METHOD
    ys[n]   = ys[n-1] + ydot[n]   * dt   # SEMI-IMPLICIT METHOD
  • (Fig. 5.5): Euler sits slightly above the analytic path (“too much energy”). Semi-implicit falls well short (“too little energy”). Here the semi-implicit method has a much larger error and needs a higher to converge.
  • (Fig. 5.6): all three curves coincide, so the solution has converged. It needed a lot of time steps.
Watch out

“Semi-implicit is usually better” is not a guarantee. In this problem it is clearly worse at . Check convergence for every problem rather than trusting the method.

Interactive figure

At the picture matches handout Fig. 5.5. Drag up and the semi-implicit path creeps out to the analytic one. Parameters inferred from the handout’s plot: launch at 10 m/s and 45°, , 1 s run.

Figure Projectile with linear drag: Euler, semi-implicit and analytic
Explanation Why is semi-implicit so much worse here, when it is ‘usually better’?

Write . Horizontally, each Euler velocity update multiplies by a constant, , so . The final is then a geometric series:

Euler’s limit equals the analytic asymptote exactly. That is a lucky property of this particular problem. Semi-implicit is short by the fraction . In Fig. 5.5 it stops near 0.635 m instead of 0.707 m, so .

The “more stable, better energy” advantage of semi-implicit applies to oscillating, energy-conserving systems such as the bouncing ball below. It is not a rule for every problem.

  • Only the acceleration lines change: compute and from the previous step, then update both components side by side.
  • Semi-implicit was much worse at and needed to converge. No method is always better, so check convergence.

Example: bouncing ball

This system must switch between two equations of motion. In free fall only the weight acts. During the bounce, a spring force (stiffness ) acts as well. The free body diagrams include the D’Alembert force (Inertial (D'Alembert) force), drawn opposite to positive .

Summary k m H y 0 FBD: free fall mg mÿ FBD: contact Fspring = −ky mg mÿ

is measured upwards from the top of the unloaded spring. Contact means , in which case pushes up. Real forces are red; the D’Alembert force is teal and dashed.

Figure Bouncing ball: summary and free body diagrams
Equation Bouncing ball: the two equations of motion memorise
Show derivation

Use the D'Alembert form of Newton's second law form on each FBD, taking upwards as positive.

  • Free fall: , so .
  • Contact: the spring (linear, stiffness : Stiffness) is compressed by . It pushes up with . Then , so .

The ball is not attached to the spring, so the spring force is zero whenever . The spring can push but not pull.

The switching is a simple if in the code:

for n in range(1,N):
    if y[n-1] < 0:                         # BOUNCE:     m y'' = -mg - ky
        yddot[n-1] = -g - k/m*y[n-1]
    else:                                  # FREE FALL:  m y'' = -mg
        yddot[n-1] = -g

    ydot[n] = ydot[n-1] + yddot[n-1] * dt
    y[n]    = y[n-1]    + ydot[n-1]  * dt  # EULER'S METHOD
#   y[n]    = y[n-1]    + ydot[n]    * dt  # SEMI-IMPLICIT METHOD

Only the last line needs changing (ydot[n-1] becomes ydot[n]) to turn this into the semi-implicit method.

Four simulations of the bouncing ball (handout Fig. 5.18)

Four candidate runs of the same 1 m drop. Panel a: peaks slowly growing. Panel b: no energy lost, which is the physically correct one (ticked). Panel c: completely unstable. Panel d: slowly losing height.

Figure Four simulations of the bouncing ball (handout Fig. 5.18)

There is no damping in this model, so energy must be conserved and every bounce must return to the same height . This is the “aspect you know the answer to” from Two standard checks on a numerical solution. Only panel b passes. In panel a the numerics create energy, in panel d they destroy it, and in panel c they blow up.

Interactive figure

The model is a 1 m drop onto a spring with ; the green dashed reference uses a very small step. Euler gains energy (peaks grow) and blows up for large . Semi-implicit slowly loses height. Both approach the reference, panel (b), as shrinks. Watch , which should be 1.

Figure Bouncing ball: method and time step
Explanation Why does Euler gain energy and semi-implicit lose it in free fall?

For constant both methods get exactly. The difference is in . Summing the position updates, as for the car, gives

  • Euler’s ball is always slightly too high. It reaches the spring later, and therefore faster, so it gains energy on every fall and every rise.
  • Semi-implicit’s ball is too low. It arrives earlier and slower, so it loses energy.

This is the same “too much / too little energy” pattern seen in the car and the projectile.

Explanation Why can a large Δt make the bounce explode (panel c)?

The stiff spring sets a very short timescale. Contact lasts roughly half a period of mass-on-spring oscillation, ; vibration is covered later in the course. Here that is about 35 ms. If is not much smaller than this, one step can carry the ball deep into the spring. The next step then applies a huge force , launching it with far more energy than it had. The time step must resolve the fastest thing happening in the simulation, not just the slow free fall.

Try now
  • Switch equations of motion with an if on the previous state: spring force only when (it can push but not pull).
  • Euler → semi-implicit: change only the position line to use ydot[n].
  • Check: with no damping the bounce height must stay at . Growing peaks mean numerical energy gain, shrinking peaks mean numerical loss, and blow-up means is too big for the short contact time.

Summary

  • Equations of motion can be too complicated to solve analytically. Numerical integration finds solutions to otherwise impossible problems.
  • There are many methods. Two very simple first-order ones were introduced: Euler and Euler–Cromer (semi-implicit).
  • The solution error of first-order methods is proportional to the time-step length.
  • Every numerical simulation needs two checks:
    • the answer agrees with properties that can be checked analytically;
    • the answer has converged.
  • It helps to compare simulations with similar systems whose analytic solution you know, to test the reliability of the code.