Root Finding by Interval Halving, Exercise 2 template

Contents

3. Root Finding by Interval Halving, Exercise 2 template#

Author: …

Last revised on August 26, 2024

Introduction#

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

Create a Python function implementing this better algorithm, with usage

(root, errorBound) = bisection2(f, a, b, errorTolerance)

Note that this also improves the output, by giving information about the accuracy of the output result: we should always aim at this from now on.

(Again I have changed the names of the error tolerance and error bound from \(E_{tol}\) and \(E_{max}\), both to be more descriptive and to avoid subscripts. Note also the “camel case” style: concatenating words [since spaces are not allowed in names] and capitalizing each new word. Another popular option is to replace each space in a descriptive phrase by the underscore “_” as with error_tolerance.)

Test it with the above example: \(f(x) = x - \cos x\), \([a, b] = [-1, 1]\), this time accurate to within \(10^{-4}\).

Use the fact that there is a solution in the interval \((-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 bisection2(f, a, b, errorTolerance):
    """
    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 answers without having done any real work!

    Inputs:
    f: a continuous function from and to real values
    a: to be continued ...
    """
    root=(a+b)/2
    errorBound=(b-a)/2
    return (root, errorBound)

Aside: look what the function help does:

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

bisection2(f, a, b, errorTolerance)
    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 answers without having done any real work!
    
    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 error tolerance errorTolerance