{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Root Finding by Interval Halving, Exercise 1 template\n",
"\n",
"Author: ...\n",
"\n",
"Last revised on August 26, 2024"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction\n",
"\n",
"This is a template for working on Exercise 1 of Section 1.1, *Root Finding by Interval Halving*"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create a Python function `bisection1` which implements the first algorithm for bisection, performing a fixed number `iterations` of iterations.\n",
"\n",
"(The iteration count was called $N$ in the mathematical description,\n",
"but in code it is encouraged to use descriptive names.)\n",
"\n",
"The usage will be:\n",
"\n",
" root = bisection1(f, a, b, iterations)\n",
" \n",
"Test it with the example:\n",
"$f(x) = x - \\cos x = 0$, $[a, b] = [-1, 1]$"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# We will often need resources from the modules numpy and pyplot:\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# We can also import items from a module individually, so they can be used by \"first name only\".\n",
"# This will often be done for mathematical functions.\n",
"from numpy import cos"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"def bisection1(f, a, b, iterations):\n",
" \"\"\"\n",
" This is a \"stub\": it functions in that it is \"syntactically correct\",\n",
" but does not do the right thing.\n",
" Instead it gives the best available answer without having done any real work!\n",
" \n",
" Inputs:\n",
" f: a continuous function from and to real values\n",
" a: to be continued ...\n",
" \"\"\"\n",
" root=(a+b)/2\n",
" return root"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Aside: look what the function `help` does:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on function bisection1 in module __main__:\n",
"\n",
"bisection1(f, a, b, iterations)\n",
" This is a \"stub\": it functions in that it is \"syntactically correct\",\n",
" but does not do the right thing.\n",
" \n",
" Inputs:\n",
" f: a continuous function from and to real values\n",
" a: to be continued ...\n",
"\n"
]
}
],
"source": [
"help(bisection1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now test this, by first defining the needed inputs `f`, `a`, `b` and the iteration count `iterations` ..."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.18"
}
},
"nbformat": 4,
"nbformat_minor": 4
}