If you are in Year 5 of the applied sciences liceo (the Italian academic high school with a science and computing focus), in the first term computer science reaches numerical methods: finding the zeros of a function with the computer, when the equation cannot be solved with a formula. The written test or lab assignment on this block usually falls six to nine weeks from now, between late November and December. There is time, and the topic is one of the best in the programme, because for the first time the code you write gives a result you can check with a calculator.
Every year in my lessons I see the same two obstacles: understanding why the method converges, and writing a loop with a sensible stopping criterion. I always use the same example, the simplest there is: , whose positive root is . We already know the answer, so we can see whether the method finds it.
If Python is still a bit new to you, start from programming in Python from scratch. To think about loops and conditions before the code, you need flowcharts and pseudocode. For another example of an algorithm with a cost comparison, see sorting algorithms.
The bisection method
The idea comes from the intermediate value theorem: if is continuous on and and have opposite signs, there is at least one root in the interval. You take the midpoint and keep the half where the sign changes. Repeat.
For on : and , opposite signs, so we can start.
| Step | a | b | m | f(m) |
|---|---|---|---|---|
| 1 | 1 | 2 | 1.5 | 0.25 |
| 2 | 1 | 1.5 | 1.25 | -0.4375 |
| 3 | 1.25 | 1.5 | 1.375 | -0.109375 |
| 4 | 1.375 | 1.5 | 1.4375 | 0.0664 |
| 5 | 1.375 | 1.4375 | 1.40625 | -0.0225 |
After 5 steps the root lies in : the maximum error is . At every step the interval halves, so after steps the width is . To get an error below from an interval of width 1 you need , that is (indeed ).
The Newton–Raphson method
Newton’s method uses the derivative: from the point you draw the tangent to the graph and take the point where it meets the -axis. The formula is:
For the derivative is , and the formula becomes . Let us start from :
After only 3 steps there are 11 correct digits. A useful observation for the test: the number of correct digits roughly doubles at every step (error: about , then , then ). Bisection, by contrast, gains just one bit (a factor of 2) per step.
The Python code
I tested these functions with python3 on the example above.
def f(x):
return x * x - 2
def df(x):
return 2 * x
def bisection(f, a, b, tol=1e-6, max_iter=100):
if f(a) * f(b) > 0:
raise ValueError("f(a) and f(b) must have opposite signs")
for i in range(1, max_iter + 1):
m = (a + b) / 2
if f(m) == 0 or (b - a) / 2 < tol:
return m, i
if f(a) * f(m) < 0:
b = m
else:
a = m
return (a + b) / 2, max_iter
def newton(f, df, x0, tol=1e-10, max_iter=50):
x = x0
for i in range(1, max_iter + 1):
d = df(x)
if d == 0:
raise ZeroDivisionError("zero derivative")
x_new = x - f(x) / d
if abs(x_new - x) < tol:
return x_new, i
x = x_new
return x, max_iter
print(bisection(f, 1, 2))
print(newton(f, df, 1.5))
Output: bisection gives about 1.4142141 in 20 iterations, Newton 1.4142135623730951 in 4 iterations. With a tolerance of bisection needs 34. For the same precision, Newton does less than 15% of the work.
A few choices you should be able to explain in the lab:
- the functions receive
fas a parameter, so the same code works for any equation; max_iteravoids an infinite loop if the method does not converge;- the initial sign check in
bisectionprotects against intervals that do not contain a root; - in
newtonthed == 0check avoids division by zero.
Stopping criteria
A numerical loop must know when to stop. There are three criteria, often combined:
- Width of the interval (bisection): .
- Difference between approximations: .
- Residual: . Careful: if the function is very flat near the root, a small residual does not guarantee an close to the root.
Always add a maximum number of iterations: it is the last safety net.
Comparison and limits
| Bisection | Newton | |
|---|---|---|
| Needs | An interval with a sign change | The derivative and a starting point |
| Convergence | Always, but slow (one bit per step) | Very fast, if it starts close |
| Risks | Few | Zero derivative, distant starting point, divergence |
| Cost per step | One evaluation of | and |
In practice: Newton is faster, bisection is more robust. A typical mistake is to start Newton from for . The derivative is 0 and the code raises the exception. With the first step sends the point to , and more steps are needed to get back near the root: the method works, but the starting point matters.
If you want a level beyond high school, where error and convergence are also studied formally, you will find it in numerical methods for the exam. For the calculus behind Newton’s method, it is worth revising derivatives explained well.
A complete exercise
Find as the positive root of , using Newton from . The derivative is and the step is .
The exact value is : at the third step the error is already below . How many iterations would bisection have used on for the same tolerance? You need , that is (). The comparison 3 against 27 is the answer many teachers want to hear about the speed of convergence.
A warning about the code: if you are asked to modify it for , only f and df change, not the two method functions. If you had to touch bisection or newton, something is not general.
Test yourself
Before a test, redo by hand three iterations of Newton for from and then check with the code. Then try the free practice test on high school tests. If you want to go over your lab code together, we can do it in the free 30-minute introductory call with me.