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 | 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 is much bigger than , 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, :
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 is continuous and , have opposite signs, there is a root between them. Halve the interval, keep the half where the sign still changes, repeat. After steps the interval has width , so reaching a tolerance takes
For on with that is steps, known in advance. Bisection never diverges, but it gains only one bit per step.
Newton's method: fast when it works
Newton replaces by its tangent line and jumps to where the tangent crosses zero (Newton's method):
Near a simple root the number of correct digits roughly doubles each step. The risks: (division by zero), or a bad start that sends the iteration away.
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_newbisection: 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 |
|---|---|---|
| the step is tiny | is meaningless for | |
| relative step is tiny | fails at a root | |
| residual is tiny | a flat can be small far from the root | |
| give up | always include it: it turns a hang into an error |
A good default is a mixed test, (that is what math.isclose does), plus an iteration cap. Asking for below about 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:
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 and 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
Check: is too wide, is fine.
Exercise 2: One Newton step by hand
Use Newton's method on starting from . Compute and as fractions.
Answer
, ()
Solution
For , the Newton step simplifies to :
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 on (solve ) to within and prints the result and the number of steps.
Answer
after 20 steps
Solution
steps.
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 at ? What would you do in code?
Answer
, so the step divides by zero. Detect a tiny and fall back to bisection, or restart from another point.
Solution
The tangent at 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?
- It is halved
- It is squared
- It is divided by 10
- It does not shrink
Why is inaccurate for ?
- The discriminant is negative
- Python cannot take square roots of large numbers
- It subtracts two nearly equal numbers and loses most digits
- The formula only works for integers
Which stopping rule is the safest default for a numeric solver?
- Stop when f(x) == 0 exactly
- A mixed tolerance plus a maximum iteration count
- Stop after exactly 5 iterations
- Stop when