---
title: "Lab: Newton's method in code"
heading: A root finder you can trust, and the one case it can't handle
eyebrow: A5 · Lesson 35 · Lab: Newton's method in code
xp: 60
---

::: hook
Every circuit simulator, at its heart, solves equations with Newton's method: guess, follow the tangent, repeat. It's fast because the number of correct digits roughly doubles at each step. It also fails in recognizable ways when started badly. In this lab you'll write a Newton solver that knows when to stop and when to give up, use it on a diode circuit, measure how fast it converges, and watch it fail on a function where the tangent points the wrong way.
:::

::: play
- The curve is $f(x) = \tan^{-1}x$, whose only root is 0. Newton's method from $x_0$ draws a tangent and jumps to where it hits zero.
- Start at $x_0$ = 1 and the steps close in on 0. Start beyond about 1.39 and they overshoot farther each time.
- The readout is the first Newton step from your $x_0$. When is it farther from 0 than $x_0$ itself?
:::

```sim plot
view: graph
x: x = -6..6
y: y = -1.6..1.6
slider: x0 = 0.2..2 = 1
plot: atan(x) | samples: 300 | label: atan x
plot: atan(x0) + (x - x0)/(1 + x0^2) | dashed | color: ch2 | label: tangent at x0
marker: x = x0 - atan(x0)*(1 + x0^2) | label: next step
readout: next step = x0 - atan(x0)*(1 + x0^2) | digits: 4
```

::: predict
## Newton's method finds $\sqrt{2}$ from $x_0 = 1$. The error after one step is 0.086. About what is it after the next step?

- [ ] 0.043
- [x] 0.0025
- [ ] 0.0074
- [ ] 0.086, since Newton's method is linear

::: reveal
About 0.0025. Newton's method converges quadratically: each error is about $\frac{|f''|}{2|f'|}$ times the square of the last, here $\frac{1}{2\sqrt 2} \times 0.086^2 \approx 0.0026$. The next error is about $2 \times 10^{-6}$, then $10^{-12}$: the correct digits double each step.
:::
:::

::: nameit
## The method

To solve $f(x) = 0$, repeat

$$x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}$$

until the step $|x_{n+1} - x_n|$ is below a tolerance.

## When to stop, and when to give up

A good solver has three ways out:
- **converged:** the step is smaller than the tolerance;
- **too many steps:** it hasn't converged after a maximum count, so something is wrong;
- **blowing up:** $|x|$ has grown absurdly large, or $f'(x) = 0$ (a flat tangent never reaches zero).

Returning `None` for the last two, instead of a wrong number, lets the caller try something else, such as bisection.

## How fast

Near a simple root, the errors satisfy $e_{n+1} \approx C e_n^2$ with $C = \frac{|f''|}{2|f'|}$ at the root: quadratic convergence. One way to see it in data is the ratio $\frac{\ln e_{n+1}}{\ln e_n}$, which approaches 2 as the errors shrink. Bisection, by contrast, halves the error each step, a ratio $e_{n+1}/e_n = \tfrac12$.

## The diode circuit

A source $V_s$ through a resistor $R$ into a diode gives $f(V) = \frac{V_s - V}{R} - I_s(e^{V/V_T} - 1) = 0$. Its exponential makes a bad first guess dangerous: starting at 1 V, $e^{V/V_T}$ is $e^{38.7}$, and the first step lands far away. Starting near 0.6 to 0.8 V, Newton converges in a handful of steps.
:::

::: example
## Run Newton's method on $x^2 - 2$ from $x_0 = 1$ and list the errors.

::: solution
1. **Iterate and list the errors.** Each row is one Newton step and its distance from $\sqrt{2}$:

| $n$ | $x_n$ | error |
|---|---|---|
| 1 | 1.5 | $8.6 \times 10^{-2}$ |
| 2 | 1.416 667 | $2.5 \times 10^{-3}$ |
| 3 | 1.414 216 | $2.1 \times 10^{-6}$ |
| 4 | 1.414 214 | $1.6 \times 10^{-12}$ |

2. **Compare each error with the one before.** Each is about $0.35$ times the square of the one before, the constant $\frac{1}{2\sqrt2}$.

**Answer:** the errors are $8.6 \times 10^{-2}$, $2.5 \times 10^{-3}$, $2.1 \times 10^{-6}$ and $1.6 \times 10^{-12}$, each about 0.35 times the square of the last.
:::
:::

::: example
## A 5 V source drives a 1 kΩ resistor and a diode with $I_s = 10^{-14}$ A and $V_T$ = 25.85 mV. Solve for the diode's voltage by Newton's method from 0.8 V.

::: solution
1. **The function.**
   $$\begin{aligned} f(V) = &\frac{5 - V}{1000} \\ &- 10^{-14}(e^{V/0.025\,85} - 1) \end{aligned}$$
2. **Its derivative.**
   $$\begin{aligned} f'(V) = &-0.001 \\ &- \frac{10^{-14}}{0.025\,85}e^{V/0.025\,85} \end{aligned}$$
3. **The first steps.** From 0.8 V the diode's current is enormous, so the first steps walk down by about one $V_T$ each, then converge fast once the current is in range.
4. **Result.** After 10 steps the voltage settles at 0.692 49 V, with 4.31 mA flowing.
5. **Compare with bisection.** Bisection on $[0, 1]$ needs about 40 steps for the same precision.

**Answer:** the diode's voltage is 0.692 49 V, with 4.31 mA flowing.
:::
:::

::: check
given: e = 0.01 | 0.05 | 0.1; C = 0.35 | 1 | 2
answer: C*e^2
tolerance: 0.5%

## Near a root, Newton's errors follow $e_{n+1} \approx Ce_n^2$ with $C$ = {C}. If $e_n$ = {e}, what is $e_{n+1}$?

::: right
Right. $Ce_n^2$ = {answer}: the error squares.
:::

::: misses
- [C*e] That's linear convergence. Newton's is quadratic.
- [e/2] That's bisection.
- [any] Not yet. Square the error and multiply by $C$.
:::
:::

::: check
given: x0 = 0.5 | 1 | 1.5 | 2
answer: x0 - atan(x0)*(1 + x0^2)
tolerance: 0.5%

## Newton's method on $\tan^{-1}x$ starts at $x_0$ = {x0}. Where does the first step land?

::: right
Right. $x_0 - \tan^{-1}(x_0)(1 + x_0^2)$ = {answer}.
:::

::: misses
- [x0 - atan(x0)/(1 + x0^2)] Divide by the slope $\frac{1}{1 + x^2}$, which means multiplying by $1 + x^2$.
- [any] Not yet. $x_1 = x_0 - f(x_0)/f'(x_0)$ with $f' = 1/(1 + x^2)$.
:::
:::

::: check
kind: python

## Write `newton(f, df, x0, tol=1e-12, maxit=50)` returning `(root, steps)`. Stop when a step is smaller than `tol`. Return `(None, steps)` if it runs out of steps, if $f'(x) = 0$, or if $|x|$ exceeds $10^{10}$. Set `r = newton(lambda x: x*x - 2, lambda x: 2*x, 1.0)`.

```python starter
def newton(f, df, x0, tol=1e-12, maxit=50):
    return x0, 0

r = newton(lambda x: x*x - 2, lambda x: 2*x, 1.0)
print(r)
```

```python solution
def newton(f, df, x0, tol=1e-12, maxit=50):
    x = x0
    for n in range(1, maxit + 1):
        d = df(x)
        if d == 0:
            return None, n
        step = f(x) / d
        x -= step
        if abs(x) > 1e10:
            return None, n
        if abs(step) < tol:
            return x, n
    return None, maxit

r = newton(lambda x: x*x - 2, lambda x: 2*x, 1.0)
print(r)
```

```python tests
import math
root, n = r
assert abs(root - math.sqrt(2)) < 1e-12 and n <= 7, f"From 1, Newton should reach sqrt(2) in about 6 steps; got {r}."
root, n = newton(math.cos, lambda x: -math.sin(x), 1.0)
assert abs(root - math.pi / 2) < 1e-12, "It should find the root of cos near pi/2."
assert newton(math.atan, lambda x: 1 / (1 + x * x), 1.5)[0] is None, "From 1.5, Newton on atan runs away; it should return None."
assert newton(lambda x: x * x + 1, lambda x: 2 * x, 0.0)[0] is None, "A zero slope should return None."
assert newton(lambda x: x * x + 1, lambda x: 2 * x, 0.5, maxit=30)[0] is None, "x^2 + 1 has no real root; it should give up."
```

::: right
Right. Knowing when to give up is what makes a solver safe to build on.
:::
:::

::: check
kind: python
given: Vs = 3 | 5 | 12; R = 470 | 1000 | 4700

## Use your `newton` (copied into the starter) to find a diode's voltage: a source `Vs` = {Vs} V through `R` = {R} Ω, $I_s = 10^{-14}$ A, $V_T$ = 0.025 85 V, starting from 0.8 V. Set `Vd` to the voltage and `I` to the current through the resistor.

```python starter
import math

def newton(f, df, x0, tol=1e-12, maxit=50):
    x = x0
    for n in range(1, maxit + 1):
        d = df(x)
        if d == 0:
            return None, n
        step = f(x) / d
        x -= step
        if abs(x) > 1e10:
            return None, n
        if abs(step) < tol:
            return x, n
    return None, maxit

Vd = 0
I = 0
print(Vd, I)
```

```python solution
import math

def newton(f, df, x0, tol=1e-12, maxit=50):
    x = x0
    for n in range(1, maxit + 1):
        d = df(x)
        if d == 0:
            return None, n
        step = f(x) / d
        x -= step
        if abs(x) > 1e10:
            return None, n
        if abs(step) < tol:
            return x, n
    return None, maxit

Is, VT = 1e-14, 0.02585
f = lambda V: (Vs - V) / R - Is * (math.exp(V / VT) - 1)
df = lambda V: -1 / R - Is / VT * math.exp(V / VT)
Vd, steps = newton(f, df, 0.8)
I = (Vs - Vd) / R
print(Vd, I, steps)
```

```python tests
import math
assert abs((Vs - Vd) / R - 1e-14 * (math.exp(Vd / 0.02585) - 1)) < 1e-12, "At the solution the resistor's current must equal the diode's."
assert 0.55 < Vd < 0.75, f"A silicon diode at milliamps sits near 0.6 to 0.7 V; got {Vd}."
assert abs(I - (Vs - Vd) / R) < 1e-15, "I should be the current through the resistor."
```

::: right
Right. The same few lines, run at every time step, are what a circuit simulator does with every diode and transistor.
:::
:::

::: check
kind: python

## Measure the order of convergence. Run Newton on $x^2 - 2$ from 1 for four steps, recording the errors $e_n = |x_n - \sqrt2|$ in a list `e`. Set `orders` to the list of $\ln e_{n+1}/\ln e_n$ for consecutive pairs, and `bisect_ratio` to the error ratio of bisection, $e_{n+1}/e_n$, measured from two bisection steps on $[1, 2]$ (take $e$ as half the bracket width).

```python starter
import math

e = []
orders = []
bisect_ratio = 0
print(e, orders, bisect_ratio)
```

```python solution
import math

x = 1.0
e = []
for _ in range(4):
    x = x - (x * x - 2) / (2 * x)
    e.append(abs(x - math.sqrt(2)))
orders = [math.log(e[k + 1]) / math.log(e[k]) for k in range(len(e) - 1)]
a, b = 1.0, 2.0
widths = []
for _ in range(2):
    m = (a + b) / 2
    if (a * a - 2) * (m * m - 2) <= 0:
        b = m
    else:
        a = m
    widths.append((b - a) / 2)
bisect_ratio = widths[1] / widths[0]
print(e, orders, bisect_ratio)
```

```python tests
import math
assert len(e) == 4 and abs(e[0] - 0.0857864) < 1e-6, f"The first error is 0.0858; got {e[:1]}."
assert len(orders) == 3 and orders[-1] > 1.8, f"The order ratios should climb toward 2; got {orders}."
assert abs(bisect_ratio - 0.5) < 1e-12, f"Bisection halves the bracket each step; got {bisect_ratio}."
```

::: right
Right. The ratio of logs heads to 2 for Newton; bisection's error ratio sits at ½ forever.
:::
:::

::: check
kind: python
given: x0 = 0.5 | 1 | 1.3 | 1.38 | 1.45 | 1.6 | 2

## Find where Newton's method on $\tan^{-1}x$ stops working. Write `converges(x0)` returning `True` if `newton` (in the starter) finds the root 0 from `x0`. Then bisect on `x0` between 1 and 2 (40 halvings) to set `edge` to the starting point where it switches from converging to diverging, and `ok = converges(x0)` for `x0` = {x0}.

```python starter
import math

def newton(f, df, x0, tol=1e-12, maxit=100):
    x = x0
    for n in range(1, maxit + 1):
        d = df(x)
        if d == 0:
            return None, n
        step = f(x) / d
        x -= step
        if abs(x) > 1e10:
            return None, n
        if abs(step) < tol:
            return x, n
    return None, maxit

def converges(x0):
    return True

edge = 0
ok = converges(x0)
print(edge, ok)
```

```python solution
import math

def newton(f, df, x0, tol=1e-12, maxit=100):
    x = x0
    for n in range(1, maxit + 1):
        d = df(x)
        if d == 0:
            return None, n
        step = f(x) / d
        x -= step
        if abs(x) > 1e10:
            return None, n
        if abs(step) < tol:
            return x, n
    return None, maxit

def converges(x0):
    r, _ = newton(math.atan, lambda x: 1 / (1 + x * x), x0)
    return r is not None and abs(r) < 1e-9

a, b = 1.0, 2.0
for _ in range(40):
    m = (a + b) / 2
    if converges(m):
        a = m
    else:
        b = m
edge = (a + b) / 2
ok = converges(x0)
print(edge, ok)
```

```python tests
assert abs(edge - 1.3917452) < 1e-4, f"The edge is where the first step lands exactly at -x0, near 1.3917; got {edge}."
assert converges(1.0) and not converges(1.5), "From 1 it converges; from 1.5 it diverges."
assert ok == (x0 < 1.3917452), "ok doesn't match this lab's start."
```

::: right
Right. Past 1.3917 each step overshoots farther than the last, and the iterates fly off to infinity, alternating sides.
:::
:::

::: check
kind: python

## Write `safe_newton(f, df, a, b, x0)`: keep a bracket $[a, b]$ where $f$ changes sign. Take a Newton step from the current point; if it lands outside the bracket (or the slope is zero), take the bracket's midpoint instead. Then shrink the bracket to the half with the sign change containing the new point, and stop when a step is below $10^{-12}$. Return the root.

```python starter
import math

def safe_newton(f, df, a, b, x0):
    return x0

print(safe_newton(math.atan, lambda x: 1 / (1 + x * x), -2, 2, 1.5))
```

```python solution
import math

def safe_newton(f, df, a, b, x0):
    x = x0
    for _ in range(200):
        d = df(x)
        xn = x - f(x) / d if d != 0 else (a + b) / 2
        if not (a < xn < b):
            xn = (a + b) / 2
        if f(a) * f(xn) <= 0:
            b = xn
        else:
            a = xn
        if abs(xn - x) < 1e-12:
            return xn
        x = xn
    return x

print(safe_newton(math.atan, lambda x: 1 / (1 + x * x), -2, 2, 1.5))
```

```python tests
import math
r = safe_newton(math.atan, lambda x: 1 / (1 + x * x), -2, 2, 1.5)
assert abs(r) < 1e-10, f"From 1.5, where plain Newton diverges, it should still find 0; got {r}."
r = safe_newton(lambda x: x**3 - 2 * x - 5, lambda x: 3 * x**2 - 2, 2, 3, 2.5)
assert abs(r - 2.0945514815423265) < 1e-10, f"x^3 - 2x - 5 has its root at 2.0946; got {r}."
f = lambda V: (5 - V) / 1000 - 1e-14 * (math.exp(V / 0.02585) - 1)
df = lambda V: -1e-3 - 1e-14 / 0.02585 * math.exp(V / 0.02585)
r = safe_newton(f, df, 0, 1, 1.0)
assert abs(r - 0.6924904) < 1e-6, f"The diode from a bad start of 1.0 V should still settle at 0.6925 V; got {r}."
```

::: right
Right. Newton's speed with bisection's guarantee: this is the shape of most production root finders.
:::
:::

::: explain
## Newton's method roughly doubles the correct digits each step near a root, yet a simulator sometimes fails to converge. How can both be true?

::: model
The doubling is a local promise: it holds once the guess is close enough to the root that the function looks like its tangent line over the distance still to go. Far from the root, the tangent can be a poor guide. A nearly flat tangent sends the next guess far away, as with $\tan^{-1}x$ beyond about 1.39, where every step overshoots more than the last. An exponential like a diode's makes this worse: from a guess a few tenths of a volt too high, the predicted current is astronomically large and the first steps are tiny or wild. So simulators combine Newton's speed near the answer with safeguards for getting there: limiting how far one step can move a junction voltage, falling back to bisection when a bracket is known, or ramping the sources up from zero so each solve starts near the last answer.
:::
:::

::: practice

::: check
given: e = 0.0001..0.2; C = 0.1..3
answer: C*e^2
tolerance: 0.5%

## Quadratic convergence: $C$ = {C}, $e_n$ = {e}. What is $e_{n+1}$?

::: misses
- [any] $Ce_n^2$.
:::
:::

::: check
given: x0 = 0.1..3
answer: x0 - atan(x0)*(1 + x0^2)
tolerance: 0.5%

## One Newton step on $\tan^{-1}x$ from {x0}?

::: misses
- [any] $x_0 - \tan^{-1}(x_0)(1 + x_0^2)$.
:::
:::
:::
