1. Root Finding by Interval Halving, Exercise 1 template#

Author: …

Last revised on August 26, 2024.

Introduction#

This is a template for working on Exercise 1 of Section 1.1, Root Finding by Interval Halving

Create a Python function bisection1 which implements the first algorithm for bisection, performing a fixed number iterations of iterations.

(The iteration count was called \(N\) in the mathematical description, but in code it is encouraged to use descriptive names.)

The usage will be:

root = bisection1(f, a, b, iterations)

Test it with the example: \(f(x) = x - \cos x = 0\), \([a, b] = [-1, 1]\)

# We will often need resources from the modules numpy and pyplot:
import numpy as np
import matplotlib.pyplot as plt

# We can also import items from a module individually, so they can be used by "first name only".
# This will often be done for mathematical functions.
from numpy import cos
def bisection1(f, a, b, iterations):
    """
    This is a "stub": it functions in that it is "syntactically correct",
    but does not do the right thing.
    Instead it gives the best available answer without having done any real work!
    
    Inputs:
    f: a continuous function from and to real values
    a: to be continued ...
    """
    root=(a+b)/2
    return root

Aside: look what the function help does:

help(bisection1)
Help on function bisection1 in module __main__:

bisection1(f, a, b, iterations)
    This is a "stub": it functions in that it is "syntactically correct",
    but does not do the right thing.
    
    Inputs:
    f: a continuous function from and to real values
    a: to be continued ...

Now test this, by first defining the needed inputs f, a, b and the iteration count iterations