Numerical root finding is the process of finding an approximate value such that for a given continuous function .
The Bisection Method
The Bisection method is a robust but slow root-finding algorithm. It works by repeatedly bisecting an interval and then selecting a subinterval in which a root must lie for further processing. It requires that the function values at the endpoints of the interval have opposite signs (Bolzano’s Theorem).
Interactive Lab
def f(x):
return x**3 - x - 2
def bisection(a, b, tol=1e-5):
if f(a) * f(b) >= 0:
return "Bisection fails (no sign change)."
while (b - a) / 2 > tol:
midpoint = (a + b) / 2
if f(midpoint) == 0:
return midpoint
elif f(a) * f(midpoint) < 0:
b = midpoint
else:
a = midpoint
return (a + b) / 2
root = bisection(1, 2)
print(f"Bisection root: {root:.6f}")
print(f"f(root): {f(root):.6e}")
python
1def f(x):
2return x**3- x -2
3
4def bisection(a, b, tol=1e-5):
5if f(a)* f(b)>=0:
6return"Bisection fails (no sign change)."
7
8while(b - a)/2> tol:
9 midpoint =(a + b)/2
10if f(midpoint)==0:
11return midpoint
12elif f(a)* f(midpoint)<0:
13 b = midpoint
14else:
15 a = midpoint
16return(a + b)/2
17
18root = bisection(1, 2)
19print(f"Bisection root: {root:.6f}")
20print(f"f(root): {f(root):.6e}")
Newton-Raphson Method
The Newton-Raphson method uses the first two terms of the Taylor series to iteratively improve an estimate.
Interactive Lab
def f(x):
return x**3 - x - 2
def df(x):
return 3*x**2 - 1
def newton(x0, tol=1e-5, max_iter=100):
x = x0
for i in range(max_iter):
delta = f(x) / df(x)
x = x - delta
if abs(delta) < tol:
return x, i
return x, max_iter
root, iterations = newton(1.5)
print(f"Newton root: {root:.6f} found in {iterations} iterations")
python
1def f(x):
2return x**3- x -2
3
4def df(x):
5return3*x**2-1
6
7def newton(x0, tol=1e-5, max_iter=100):
8 x = x0
9for i inrange(max_iter):
10 delta = f(x)/ df(x)
11 x = x - delta
12ifabs(delta)< tol:
13return x, i
14return x, max_iter
15
16root, iterations = newton(1.5)
17print(f"Newton root: {root:.6f} found in {iterations} iterations")
Knowledge Check
Which method is generally faster if a good initial guess is provided?
Answer: Newton-Raphson
Which method is generally faster if a good initial guess is provided?
Convergence and Stability
Newton’s method converges quadratically (), meaning the number of correct digits roughly doubles each iteration. However, it can fail or diverge if is near zero or if the initial guess is far from a root.
Knowledge Check
What happens to Newton's method if the derivative is zero at the current guess?
Answer: It fails due to division by zero.
What happens to Newton's method if the derivative is zero at the current guess?