TExcelTAD
Home › Algebra › Solving Equations in Code

Solving Equations in Code

A program can solve an equation in four ways: with a closed-form formula, by bisection, by Newton's method, or by handing it to a computer algebra system such as SymPy. Each one trades exactness, speed and robustness differently, and the numeric ones need a tolerance: a rule for when the answer is "close enough". This lesson puts all four side by side on the same problems.

Four tools

Method Gives Needs Typical use
Closed form exact or float formula a known formula (linear, quadratic…) game physics, geometry, the inner loop
Bisection an interval that shrinks by half each step a sign change on [a,b][a, b] robust fallback, monotonic problems
Newton's method very fast convergence near a root the derivative and a good start sqrt in hardware, optimisation, physics solvers
SymPy solve / nsolve exact symbolic answers, or high precision an expression checking, deriving formulas, offline tools

Closed form, done carefully

The quadratic formula is a closed form, but the textbook version can lose almost all its digits. When b2b^2 is much bigger than 4ac4ac, −b+b2−4ac-b + \sqrt{b^2 - 4ac} subtracts two nearly equal numbers (catastrophic cancellation). The stable version computes the "big" root first and gets the other from the product of the roots, x1⋅x2=c/ax_1 \cdot x_2 = c/a:

q=−b+sign⁡(b)⋅b2−4ac2x1=qax2=cq\begin{aligned} q &= -\frac{b + \operatorname{sign}(b) \cdot \sqrt{b^2 - 4ac}}{2} \\ x_1 &= \frac{q}{a} \qquad x_2 = \frac{c}{q} \end{aligned}
python · try it yourself
import math

a, b, c = 1.0, 1e8, 1.0             # roots ≈ −1e8 and ≈ −1e-8
d = math.sqrt(b * b - 4 * a * c)
naive_small = (-b + d) / (2 * a)

q = -(b + math.copysign(d, b)) / 2
stable_big, stable_small = q / a, c / q

print("naive  small root:", naive_small)
print("stable small root:", stable_small)
print("stable big root  :", stable_big)
print("residual naive :", a * naive_small**2 + b * naive_small + c)
print("residual stable:", a * stable_small**2 + b * stable_small + c)
naive  small root: -7.450580596923828e-09
stable small root: -1e-08
stable big root  : -100000000.0
residual naive : 0.2549419403076172
residual stable: 1.1102230246251565e-16

The naive small root is about 25% off; the stable one is correct to the last digit.

Bisection: slow and sure

If ff is continuous and f(a)f(a), f(b)f(b) have opposite signs, there is a root between them. Halve the interval, keep the half where the sign still changes, repeat. After nn steps the interval has width (b−a)/2n(b - a)/2^n, so reaching a tolerance ε\varepsilon takes

n=⌈log⁡2b−aε⌉ stepsn = \left\lceil \log_2 \frac{b - a}{\varepsilon} \right\rceil \ \text{steps}

For f(x)=x3+x−3f(x) = x^3 + x - 3 on [1,2][1, 2] with ε=10−10\varepsilon = 10^{-10} that is ⌈log⁡21010⌉=34\lceil \log_2 10^{10} \rceil = 34 steps, known in advance. Bisection never diverges, but it gains only one bit per step.

Newton's method: fast when it works

Newton replaces ff by its tangent line and jumps to where the tangent crosses zero (Newton's method):

xn+1=xn−f(xn)f′(xn)here f′(x)=3x2+1x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)} \qquad \text{here } f'(x) = 3x^2 + 1

Near a simple root the number of correct digits roughly doubles each step. The risks: f′(x)=0f'(x) = 0 (division by zero), or a bad start that sends the iteration away.

python · try it yourself
import math

f = lambda x: x**3 + x - 3
df = lambda x: 3 * x**2 + 1

a, b, tol, steps = 1.0, 2.0, 1e-10, 0
while b - a > tol:
    m = (a + b) / 2
    if f(a) * f(m) <= 0:
        b = m
    else:
        a = m
    steps += 1
print(f"bisection: {(a + b) / 2:.12f} after {steps} steps")
print("predicted steps:", math.ceil(math.log2(1 / tol)))

x = 1.0
for i in range(1, 7):
    x_new = x - f(x) / df(x)
    print(f"newton {i}: {x_new:.15f}  step {abs(x_new - x):.1e}")
    if abs(x_new - x) < 1e-12 * max(1.0, abs(x_new)):
        break
    x = x_new
bisection: 1.213411662757 after 34 steps
predicted steps: 34
newton 1: 1.250000000000000  step 2.5e-01
newton 2: 1.214285714285714  step 3.6e-02
newton 3: 1.213412175782825  step 8.7e-04
newton 4: 1.213411662762407  step 5.1e-07
newton 5: 1.213411662762230  step 1.8e-13

Tolerances: when to stop

A numeric solver needs a stopping rule. The common ones, and what they protect against:

Rule Meaning Pitfall
∣xn+1−xn∣<εabs\lvert x_{n+1} - x_n \rvert < \varepsilon_\text{abs} the step is tiny εabs=10−12\varepsilon_\text{abs} = 10^{-12} is meaningless for x≈109x \approx 10^9
∣xn+1−xn∣<εrel⋅∣xn∣\lvert x_{n+1} - x_n \rvert < \varepsilon_\text{rel} \cdot \lvert x_n \rvert relative step is tiny fails at a root x=0x = 0
∣f(x)∣<εf\lvert f(x) \rvert < \varepsilon_f residual is tiny a flat ff can be small far from the root
n>max_itern > \text{max\_iter} give up always include it: it turns a hang into an error

A good default is a mixed test, ∣Δx∣<εabs+εrel⋅∣x∣\lvert \Delta x \rvert < \varepsilon_\text{abs} + \varepsilon_\text{rel} \cdot \lvert x \rvert (that is what math.isclose does), plus an iteration cap. Asking for ε\varepsilon below about 10−16⋅∣x∣10^{-16} \cdot \lvert x \rvert is pointless: that is the spacing of doubles.

SymPy: exact, then numeric

SymPy can give the exact answer, which for this cubic is a nest of cube roots, and nsolve runs a Newton-type method at any precision you ask for:

python · try it yourself
import sympy as sp

x = sp.symbols("x")
f = x**3 + x - 3
real_roots = [r for r in sp.solve(f, x) if r.is_real]
print(len(sp.solve(f, x)), "roots,", len(real_roots), "real")
print(sp.N(real_roots[0], 20))
print(sp.nsolve(f, x, 1, prec=30))
print(sp.solve(x**2 - 3*x + 1, x))
3 roots, 1 real
1.2134116627622296341
1.21341166276222963413213137738
[3/2 - sqrt(5)/2, sqrt(5)/2 + 3/2]

Tip: In production code, SciPy's scipy.optimize.brentq(f, a, b) combines bisection's guarantee with near-Newton speed and needs no derivative. It is the usual choice for a one-dimensional root with a known bracket.

In software

  • Games and graphics use closed forms in hot loops: ray–sphere hits and collision timing are quadratics.
  • Finance code finds an interest rate (IRR) with bisection or Newton, because no formula exists for it.
  • Hardware and libraries compute 1/x1/\sqrt{x} and x\sqrt{x} with a few Newton steps from a good guess.
  • ML and optimisation use Newton-like updates on gradients (gradient descent).

Exercises

Exercise 1: Steps in advance

How many bisection steps take an interval of width 8 down to width at most 0.001?

Answer

13 steps

Solution
82n≤0.001⟹2n≥8000⟹n≥log⁡28000≈12.97⟹n=13\frac{8}{2^n} \le 0.001 \quad\Longrightarrow\quad 2^n \ge 8000 \quad\Longrightarrow\quad n \ge \log_2 8000 \approx 12.97 \quad\Longrightarrow\quad n = 13

Check: 8/212≈0.001958/2^{12} \approx 0.00195 is too wide, 8/213≈0.000988/2^{13} \approx 0.00098 is fine.

Exercise 2: One Newton step by hand

Use Newton's method on f(x)=x2−10f(x) = x^2 - 10 starting from x0=3x_0 = 3. Compute x1x_1 and x2x_2 as fractions.

Answer

x1=19/6≈3.1667x_1 = 19/6 \approx 3.1667, x2=721/228≈3.16228x_2 = 721/228 \approx 3.16228 (10≈3.16228\sqrt{10} \approx 3.16228)

Solution

For f(x)=x2−10f(x) = x^2 - 10, the Newton step simplifies to x−(x2−10)/(2x)=(x+10/x)/2x - (x^2 - 10)/(2x) = (x + 10/x)/2:

x1=3+1032=19/32=196x2=196+60192=361114+3601142=721228\begin{aligned} x_1 &= \frac{3 + \frac{10}{3}}{2} = \frac{19/3}{2} = \frac{19}{6} \\ x_2 &= \frac{\frac{19}{6} + \frac{60}{19}}{2} = \frac{\frac{361}{114} + \frac{360}{114}}{2} = \frac{721}{228} \end{aligned}
python · try it yourself
from fractions import Fraction
x = Fraction(3)
for _ in range(2):
    x = (x + 10 / x) / 2
    print(x, float(x))
19/6 3.1666666666666665
721/228 3.162280701754386

Exercise 3: Bisection for a cube root (code)

Write a bisection that finds 203\sqrt[3]{20} on [2,3][2, 3] (solve x3−20=0x^3 - 20 = 0) to within 10−610^{-6} and prints the result and the number of steps.

Answer

≈2.714418\approx 2.714418 after 20 steps

Solution

⌈log⁡2(1/10−6)⌉=⌈19.93⌉=20\lceil \log_2(1/10^{-6}) \rceil = \lceil 19.93 \rceil = 20 steps.

python · try it yourself
f = lambda x: x**3 - 20
a, b, n = 2.0, 3.0, 0
while b - a > 1e-6:
    m = (a + b) / 2
    a, b = (a, m) if f(a) * f(m) <= 0 else (m, b)
    n += 1
print(f"{(a + b) / 2:.6f} {n}")
2.714418 20

Exercise 4: When Newton stalls

Why does Newton's method fail if you start f(x)=x3−3x+1f(x) = x^3 - 3x + 1 at x0=1x_0 = 1? What would you do in code?

Answer

f′(1)=3⋅12−3=0f'(1) = 3 \cdot 1^2 - 3 = 0, so the step divides by zero. Detect a tiny ∣f′∣\lvert f' \rvert and fall back to bisection, or restart from another point.

Solution

The tangent at x=1x = 1 is horizontal, so it never crosses zero. Robust solvers guard the division (if abs(dfx) < 1e-14: …) and keep a bracketing interval to fall back on. That is the idea behind Brent's method.

Test yourself

Roughly how does the error shrink per step in bisection?

  1. It is halved
  2. It is squared
  3. It is divided by 10
  4. It does not shrink

Why is (−b+b2−4ac)/2a(-b + \sqrt{b^2 - 4ac}) / 2a inaccurate for x2+108x+1=0x^2 + 10^8x + 1 = 0?

  1. The discriminant is negative
  2. Python cannot take square roots of large numbers
  3. It subtracts two nearly equal numbers and loses most digits
  4. The formula only works for integers

Which stopping rule is the safest default for a numeric solver?

  1. Stop when f(x) == 0 exactly
  2. A mixed tolerance ∣Δx∣<εabs+εrel⋅∣x∣\lvert \Delta x \rvert < \varepsilon_\text{abs} + \varepsilon_\text{rel} \cdot \lvert x \rvert plus a maximum iteration count
  3. Stop after exactly 5 iterations
  4. Stop when ∣x∣<ε\lvert x \rvert < \varepsilon