Skip to content
Tactiverge

Textbooks/Engineering Programming With Python/Chapter 7Lite (plain text) version

7Numerical methods

Version 1 · Technically checked (automated checks only) · 3 source lessons · 8 practice items

Text
All chapters and search
  1. 1. Algorithms before code
  2. 2. Values, types and formulas
  3. 3. Decisions and loops
  4. 4. Functions, tests and debugging
  5. 5. Modules, objects and data structures
  6. 6. Search, sort and cost
  7. 7. Numerical methods
  8. 8. Simulating dynamic systems

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.

Trap the root, halve the trap1.51.251.3751.437512[1.375, 1.4375] · width 0.0625
Figure 7.1. Trap the root, halve the trap. 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

This chapter is built from 3 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.

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

  • Stop when f(midpoint) == 0.
    ✓ In floating point that may never happen. Stop when the bracket is narrower than a tolerance.
  • A sign change always means a root.
    ✓ Only for a continuous function. 1/x changes sign across 0 but has no root.

Open the full 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

  • Newton's method always finds the nearest root.
    ✓ It can jump to a different root, or diverge, depending on the starting guess.
  • If a few steps look like they are settling, the answer is right.
    ✓ Check |f(x)| is small and the change between steps is below tolerance, and cap the steps.

Open the full 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

  • Sampling faster always gives a better speed estimate.
    ✓ With noise, faster sampling makes simple differences noisier. Filter or difference over longer windows.
  • The trapezium rule is exact.
    ✓ Its error shrinks like h², and it is exact only for straight-line segments.

Open the full 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

Figure 7.2 from Bisection: trap the answer, halve the trapChoose 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?
Can't use the interactive? Read a description instead

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.

Interactive figure (online). Description: 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.

Laboratory

Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.

  • Equation Lab exploration

    Equation Lab: Roots

    Find the root of x² − 2 with bisection and with Newton's method and count the steps each needs for six decimal places.

    Open Equation Lab: Roots →
  • Studio

    Code Lab

    Estimate speed from a list of position samples with central differences, then add noise and watch the estimate degrade.

    Open Code Lab →

Guided practice

Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.

Practice 1 · a fresh version every time

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.

Practice 2 · a fresh version every time

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?

steps

Practice 3

f(x) = (x − 1)² on [0, 3]. Why can't bisection start?

Practice 4 · a fresh version every time

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.

Practice 5

Newton's method on f(x) = x² − 4 starts at x₀ = 0. What happens?

Practice 6

Which statement compares bisection and Newton fairly?

Practice 7 · a fresh version every time

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.

mm/s

Practice 8 · a fresh version every time

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?

m
  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.
  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? (steps)
  3. f(x) = (x − 1)² on [0, 3]. Why can't bisection start?
    • The root is outside the bracket
    • f(0) and f(3) are both positive, so there is no sign change to trap
    • Squares can't be computed numerically
    • The bracket is too wide
  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.
  5. Newton's method on f(x) = x² − 4 starts at x₀ = 0. What happens?
    • It converges to 2
    • It converges to −2
    • It fails: f′(0) = 0, so the update divides by zero
    • It converges slowly
  6. Which statement compares bisection and Newton fairly?
    • Newton is always better
    • Bisection is guaranteed given a sign change but slow; Newton is much faster near a root but can fail from a poor start
    • Bisection needs the derivative
    • They converge at the same rate
  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. (mm/s)
  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? (m)

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 verified videos. Nothing loads from YouTube until you press play.

Starts with Newton's method as a practical root finder, then shows beautifully how sensitive it is to the starting guess.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

  • Newton’s fractal (which Newton knew nothing about) (3Blue1Brown)

Chapter summary

  • Bisection needs a sign change; each step halves the bracket, so the error bound is known in advance.
  • Newton's method uses x − f(x)/f'(x); it is fast near a root but fails when f'(x) is near zero.
  • Finite differences estimate derivatives from samples; noise is amplified by small steps.
  • The trapezoid rule adds the areas of thin trapezoids to estimate an integral from samples.

Glossary

Derivative (rate of change)
The derivative of a quantity is its instantaneous rate of change: the gradient of its graph at a point.
Integral as accumulated area
An integral adds up a rate over time: the area under a rate graph gives the total accumulated amount.
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.
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.

Definitions from the 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

  • Both functions with stopping rules and tests
  • A table of iterations to reach the tolerance
  • The failing Newton case, explained

Keep your work in your Engineering Journal; it stays private unless you choose to share it.

References

  • Jaan Kiusalaas (2013). Numerical Methods in Engineering with Python 3. Cambridge University Press.
  • Richard L. Burden and J. Douglas Faires (2011). Numerical Analysis, 9th edition. Brooks/Cole.

Publication record

Version
1
Status
Technically checked (automated checks only)
Technical review
Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
Written by
Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
Licence
All rights reserved by the founders unless a licence is approved.
Corrections
None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.