TactivergeLite

Lite / Textbooks / Engineering Programming With Python / Chapter 7

7. Numerical methods

Version 1 · Technically checked (automated checks only) · 3 source lessons · Full interactive version

Introduction

Many engineering equations have no tidy algebraic answer, so we hunt the answer numerically. Bisection traps a root between two points of opposite sign and halves the trap each step: slow but certain. Newton's method rides the tangent and converges very fast near a root, but can wander off when the slope is flat. On sampled data, finite differences estimate rates and the trapezoid rule estimates totals.

Figure 7.1. Trap the root, halve the trap (described in words)

Bisection on f(x) = x² − 2 starting from [1, 2]: midpoints 1.5, 1.25, 1.375 and 1.4375. After four halvings the root is trapped in [1.375, 1.4375], width 0.0625, around the true root 1.41421.

Explanation

Built from 3 School lessons. Each part is the lesson's own explanation.

7.1 Bisection: trap the answer, halve the trap

No formula gives the cable tension where a sag equation balances. But if you know one guess is too low and one too high, you can corner the answer to any accuracy you like.

Bracket, test, keep half

Pick a and b with f(a) * f(b) < 0. Compute the midpoint m. If f(m) has the same sign as f(a), the root is in [m, b]; otherwise it is in [a, m]. Repeat until the bracket is narrower than your tolerance.

Error you can predict

The error after k steps is at most (b − a)/2^(k+1) if you report the midpoint. That bound does not depend on the equation at all, so you can plan the computation before you run it. Each step gains one binary digit of accuracy (linear convergence).

When it fails

Bisection needs a sign change. A root where the curve only touches zero (like x² at 0) has no sign change and can't be bracketed. A discontinuity (like 1/x) can fake a sign change with no root. Always check f(a)·f(b) < 0 first and plot f if unsure.

Derivation: How many bisection steps for a given accuracy?
  1. Start with a bracket [a, b] where f(a) and f(b) have opposite signs, so a continuous f must cross zero somewhere inside (the intermediate value theorem).

  2. Each step tests the midpoint m = (a + b)/2 and keeps the half where the sign still changes. The new bracket has width (b − a)/2.

  3. After k steps the width is w_k = (b − a)/2^k. The root is always inside, so the midpoint is within w_k/2 of it.

  4. To guarantee w_k ≤ tol we need 2^k ≥ (b − a)/tol, so k = ⌈log₂((b − a)/tol)⌉.

  5. Example: [0, 2] to a width of 10⁻⁶ needs ⌈log₂(2 × 10⁶)⌉ = ⌈20.93⌉ = 21 steps. Each extra decimal place costs about 3.3 more steps.

Common mix-ups

Open the Lite lesson: Bisection: trap the answer, halve the trap

7.2 Newton's method: ride the tangent

Bisection needs about 20 steps for six decimal places. Newton's method often needs four. What's the catch?

Fast when close

From a good starting guess, Newton's method converges quadratically: the number of correct digits roughly doubles each step. For x² − 2 from 1, four steps give about 12 correct digits, where bisection on [0, 2] would need about 40.

It needs the derivative

You must supply f′(x), worked out by hand or estimated numerically. If f′(x_k) = 0 the tangent is flat and never crosses zero: the method can't continue. Guard against it and cap the number of steps.

It can run away

If the start is far from the root, or the function flattens out, the tangent can throw the next guess further away. arctan x from x₀ = 1.5 diverges. Engineers often bracket first with bisection, then switch to Newton once close, or reject any Newton step that leaves the bracket.

Derivation: Where the Newton update comes from
  1. Near a guess x_k, replace the curve by its tangent line: y ≈ f(x_k) + f′(x_k)·(x − x_k).

  2. Find where that line crosses zero: 0 = f(x_k) + f′(x_k)·(x − x_k).

  3. Solve for x: x_{k+1} = x_k − f(x_k)/f′(x_k). This needs f′(x_k) ≠ 0.

  4. For f(x) = x² − c, f′(x) = 2x, so x_{k+1} = x_k − (x_k² − c)/(2x_k) = (x_k + c/x_k)/2: average the guess with c divided by the guess.

  5. Near a simple root the error obeys e_{k+1} ≈ C·e_k², so an error of 10⁻³ becomes about 10⁻⁶, then 10⁻¹². That's quadratic convergence.

Common mix-ups

Open the Lite lesson: Newton's method: ride the tangent

7.3 Speed from position, distance from speed: calculus on samples

Your encoder gives position every 10 ms. Differentiate to get speed and the plot turns into hair. Integrate speed to get distance and it's beautifully smooth. Why the difference?

Derivatives from differences

Forward difference: (x[i+1] - x[i]) / h, an estimate of the speed between two samples. Central difference: (x[i+1] - x[i-1]) / (2 * h), centred on sample i and usually more accurate for smooth data (its error shrinks like h² rather than h).

Integrals from trapezia

Join neighbouring samples with straight lines and add the areas: h * (v[0]/2 + v[1] + ... + v[-2] + v[-1]/2). For speed samples this gives distance; for power samples, energy. Its error shrinks like h² for smooth data.

Noise changes the advice

On clean data, smaller h is always better. On noisy data, differencing divides the noise by h, so too-small steps make speed estimates useless. Integrate when you can, smooth before you differentiate, and always state the sample interval in your report.

Derivation: Why differences amplify noise
  1. Each reading is x_i + n_i, where the noise n_i is at most ε in size.

  2. Forward difference: ((x_{i+1} + n_{i+1}) − (x_i + n_i))/h = (x_{i+1} − x_i)/h + (n_{i+1} − n_i)/h.

  3. The noise term can be as large as 2ε/h. Halving h doubles it.

  4. The trapezium rule multiplies each reading by h and adds them, so noise enters as h·Σn_i. Random noise partly cancels in the sum: integration smooths, differentiation sharpens.

  5. So choose h large enough that 2ε/h is acceptable, or smooth the readings first (for example with a moving average), or use a central difference over 2h.

Common mix-ups

Open the Lite lesson: Speed from position, distance from speed: calculus on samples

Worked examples

Bisection: trap the answer, halve the trap: example 1

Find √2 as the root of x² − 2 on [0, 2] to a width of 10⁻⁶.

Solution

import math


def bisect_root(f, a, b, tol=1e-6, max_steps=100):
    """Root of f in [a, b] by bisection. Requires f(a) and f(b) of opposite sign."""
    fa = f(a)
    if fa * f(b) >= 0:
        raise ValueError("f(a) and f(b) must have opposite signs")
    steps = 0
    while b - a > tol and steps < max_steps:
        m = (a + b) / 2
        fm = f(m)
        if fm == 0:
            return m, steps + 1
        if (fm > 0) == (fa > 0):
            a, fa = m, fm
        else:
            b = m
        steps += 1
    return (a + b) / 2, steps


root, k = bisect_root(lambda x: x * x - 2, 0, 2)
print(round(root, 6), k, math.ceil(math.log2(2 / 1e-6)))   # 1.414214 21 21
Newton's method: ride the tangent: example 1

Newton's method with a step limit and a flat-slope guard, compared with the true root.

Solution

import math


def newton(f, df, x, tol=1e-12, max_steps=20):
    """Return (estimate, steps). Raises ValueError on a flat tangent or no convergence."""
    for step in range(1, max_steps + 1):
        slope = df(x)
        if slope == 0:
            raise ValueError(f"flat tangent at x = {x}")
        x_new = x - f(x) / slope
        if abs(x_new - x) < tol:
            return x_new, step
        x = x_new
    raise ValueError("did not converge")


root, steps = newton(lambda x: x * x - 2, lambda x: 2 * x, 1.0)
print(root, steps, abs(root - math.sqrt(2)) < 1e-15)   # 1.414213562373095 6 True

try:
    newton(math.atan, lambda x: 1 / (1 + x * x), 1.5)
except (ValueError, OverflowError) as err:
    print("arctan from 1.5:", type(err).__name__)
Speed from position, distance from speed: calculus on samples: example 1

Differentiate and integrate clean and noisy samples of x = 0.2t² (metres).

Solution

import random

random.seed(1)
h = 0.01
t = [i * h for i in range(201)]                 # 0 to 2 s
x = [0.2 * ti ** 2 for ti in t]
x_noisy = [xi + random.uniform(-0.0005, 0.0005) for xi in x]

i = 100                                          # t = 1.0 s, true speed 0.4 m/s
fwd = (x[i + 1] - x[i]) / h
cen = (x[i + 1] - x[i - 1]) / (2 * h)
fwd_noisy = (x_noisy[i + 1] - x_noisy[i]) / h
print(round(fwd, 4), round(cen, 4), round(fwd_noisy, 3))

v = [0.4 * ti for ti in t]                       # true speed samples
distance = h * (v[0] / 2 + sum(v[1:-1]) + v[-1] / 2)
print(round(distance, 6))                        # 0.8, exact: 0.2 * 2**2 = 0.8

The clean forward difference is 0.402 (off by 0.2h), the central difference is 0.4, and the noisy forward difference can be off by up to 0.1 m/s.

Interactive figures, in words

Figure 7.2 from Bisection: trap the answer, halve the trap

Choose x² − 2 and Bisection. Step ten times and watch the lavender bracket and the error column. Then move the ends so f(a) and f(b) have the same sign. Finally try cos x − x: does the bracket still halve at the same rate?

The stepper plots f(x) = x² − 2 on 0 to 3 with a lavender bracket. Each bisection step halves the bracket: [0, 2], [1, 2], [1, 1.5], [1.25, 1.5] and so on, closing in on 1.41421. With ends that give f the same sign, the stepper reports that bisection cannot start.

The interactive versions are in the full chapter.

Laboratory

These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.

Practice

Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.

  1. A cable tension must satisfy f(x) = x**2 - 11 = 0. Bisection starts on [1, 4] (f(1) < 0 < f(4)), tests the midpoint each step and keeps the half where the sign changes. What midpoint is tested in step 2? Give 4 decimal places.
    Answer it in “Bisection: trap the answer, halve the trap”
  2. Bisection starts from the bracket [0, 2] and stops once the bracket width is at most 0.05. What is the smallest number of steps that guarantees this?
    Answer it in “Bisection: trap the answer, halve the trap”
  3. f(x) = (x − 1)² on [0, 3]. Why can't bisection start?
    Answer it in “Bisection: trap the answer, halve the trap”
  4. A microcontroller finds a vector length L = √12 with Newton's method on f(x) = x**2 - 12, using x = x - (x**2 - 12) / (2*x). Starting from x0 = 1, what is x after 2 iterations? Give 4 decimal places.
    Answer it in “Newton's method: ride the tangent”
  5. Newton's method on f(x) = x² − 4 starts at x₀ = 0. What happens?
    Answer it in “Newton's method: ride the tangent”
  6. Which statement compares bisection and Newton fairly?
    Answer it in “Newton's method: ride the tangent”
  7. A linear-axis encoder logs position every 0.1 s: x = [11, 20, 29, 32, 38, 45] mm. Estimate the speed at sample index 4 using a forward difference (x[i+1] - x[i]) / h, in mm/s.
    Answer it in “Speed from position, distance from speed: calculus on samples”
  8. A rover logs wheel speed every 2 s: v = [1, 1, 5, 5.5] m/s. Using the trapezium rule, how far did it travel between the first and last sample, in metres?
    Answer it in “Speed from position, distance from speed: calculus on samples”

Engineering applications

Solving circuits

Circuit simulators solve the nonlinear equations of diodes and transistors with Newton's method at every time step, falling back to safer, slower steps when the tangent misleads.

Distance from speed

A data logger records speed ten times a second. The trapezoid rule adds those samples into the distance travelled, and the same idea turns a power log into energy used.

Watch (optional)

Streaming video uses a lot of data. Everything you need is in the text.

Summary

Glossary

Derivative (rate of change)
The derivative of a quantity is its instantaneous rate of change: the gradient of its graph at a point. Field Guide
Integral as accumulated area
An integral adds up a rate over time: the area under a rate graph gives the total accumulated amount. Field Guide
Floating-point rounding and comparison
Most decimal fractions cannot be stored exactly in binary floating point, so tiny rounding errors appear and == between floats is unreliable. Field Guide
The math module
Python's built-in math module provides constants such as pi and e and functions such as sqrt, sin, cos, atan2, log10, hypot, radians and degrees. Field Guide

Project: A root-finder you trust

Write bisection and Newton's method as functions with a tolerance and a maximum number of iterations. Use them to find the voltage at which an LED model draws 20 mA, compare the iteration counts, and show one starting point where Newton fails and bisection does not.

Deliverables

Write it up on paper or in your own notes. Lite never stores what you write.

References

← 6. Search, sort and cost8. Simulating dynamic systems →