"Bisection search is a basic algorithm for finding zeroes of [continuous functions](https://en.wikipedia.org/wiki/Continuous_function). Given a function f we first look for an interval $[a,b]$ such that either $f(a) < 0 \\textrm{ and } f(b) > 0,$ or $f(a) > 0 \\textrm{ and } f(b) < 0.$\n",

"\n",

"Then, since $f$ is continuous, there must be a solution point $x$ in $[a,b]$ such that $f(x)=0.$\n",

"To make the interval tighter around $x$, we check the value at the midpoint $c = \\frac{a + b}{2}.$\n",

"\n",

"For simplicity, let us assume that $f(a)<0,$ and $f(b)>0.$ If the opposite is true, we can just switch the roles of $a$ and $b$ in the following.\n",

"\n",

"If $f(c)<0$ then we can exchange $a$ for $c$ and start over with the smaller interval $[c,b]$. Likewise, if $f(c)>0$ then we can exchange $b$ for $c$ and start over with $[a,c]$.\n",

"\n",

"In both cases, we end up with an interval of length $\\frac{b-a}{2},$ half of the original search interval. Crucially, $f$ has values of opposite signs at the endpoints of this interval, so the interval still contains an $x$ such that $f(x)=0.$ \n",

"\n",

"\n",

"\n",

"We can summarize the algorithm in the following pseudocode:\n",

"\n",

"- 1: Pick a starting interval $[a, b]$\n",

"- 2: If $f(a)$ and $f(b)$ have the same sign, stop the program and report an error with the starting interval.\n",

"- 4: Replace either $a$ or $b$ with $c$ according to the rules above.\n",

"- 5: If the interval is small enough, stop. Otherwise, start over from step 3 with the smaller interval.\n",

" \n",

"In this exercise, you will use `if-elif-else` statements to answer input from the user. Consider the use of bisection search to find a zero of the function $f(x)=(x−1)(x−3)$ with starting interval $[-1,2]$.\n",

"\n"

]

},

{

"cell_type": "markdown",

"metadata": {

"deletable": false,

"editable": false,

"run_control": {

"frozen": true

}

},

"source": [

"### Task a) "

]

},

{

"cell_type": "markdown",

"metadata": {

"deletable": false,

"editable": false,

"run_control": {

"frozen": true

}

},

"source": [

"Make a program that asks the user which number the method converges to. If the user answers 1, *print* `Great! Correct answer `. Otherwise, *print* `Wrong.`\n",

"\n",

"Example run:\n",

"```\n",

"Which number does the method converge to? 1\n",

"Great! Correct answer.\n",

" \n",

"Which number does the method converge to? 3\n",

"Wrong.\n",

"```\n",

"**Write code in the block below**"

]

},

{

"cell_type": "code",

"execution_count": null,

"metadata": {},

"outputs": [],

"source": [

"# write code for task a) here\n",

"\n",

"\n",

"\n"

]

},

{

"cell_type": "markdown",

"metadata": {

"deletable": false,

"editable": false,

"run_control": {

"frozen": true

}

},

"source": [

"### Task b)"

]

},

{

"cell_type": "markdown",

"metadata": {

"deletable": false,

"editable": false,

"run_control": {

"frozen": true

}

},

"source": [

"The two zeroes of $f$ are clearly 1 and 3. Make a program that asks the user for a lower and upper limit for the starting interval and checks if the interval contains none, one or both of the zeroes.\n",

"\n",

"Example run:\n",

"```\n",

"Lower limit of interval: -1000\n",

"Upper limit of interval: 0.5\n",

"There is no zero between -1000 and 0.5.\n",

" \n",

"Lower limit of interval: 2\n",

"Upper limit of interval: 4\n",

"There is one zero between 2 and 4.\n",

" \n",

"Lower limit of interval: 0\n",

"Upper limit of interval: 3.5\n",

"There are two zeroes between 0 and 3.5.\n",

"```\n",

"**Write code in the block below**"

]

},

{

"cell_type": "code",

"execution_count": null,

"metadata": {},

"outputs": [],

"source": [

"# Write code for task b) here\n",

"\n",

"\n",

"\n"

]

},

{

"cell_type": "markdown",

"metadata": {

"deletable": false,

"editable": false,

"run_control": {

"frozen": true

}

},

"source": [

"### Task c)"

]

},

{

"cell_type": "markdown",

"metadata": {

"deletable": false,

"editable": false,

"run_control": {

"frozen": true

}

},

"source": [

"We will now work toward making an implementation of bisection search.\n",

"Make a program that asks the user for a lower and upper limit for the starting interval. Make a variable $\\mathtt{f1} = (x_{\\mathrm{low}}-1)(x_{\\mathrm{low}}-3)$ and a variable $\\mathtt{f2} = (x_{\\mathrm{high}}-1)(x_{\\mathrm{high}}-3)$ where $x_{low}$ is the lower limit and $x_{high}$ the upper limit.\n",

"\n",

"If `f1*f2 < 0`, the interval is a valid starting interval. If this is the case, do **one** iteration of bisection search (i.e. points 3 and 4 of the pseudoalgorithm) and print the new interval. Otherwise, print `Invalid starting interval`. "

]

},

{

"cell_type": "markdown",

"metadata": {

"deletable": false,

"editable": false,

"run_control": {

"frozen": true

}

},

"source": [

"Run example:\n",

"```\n",

"Lower limit of interval: 2\n",

"Upper limit of interval: 5\n",

"There is a zero between 2 and 3.5.\n",

" \n",

"Lower limit of interval: 0\n",

"Upper limit of interval: 5\n",

"Invalid starting interval.\n",

"```\n",

"\n",

"**Write code in the block below**"

]

},

{

"cell_type": "code",

"execution_count": null,

"metadata": {},

"outputs": [],

"source": [

"# Write code for task c) here\n",

"\n",

"\n",

"\n"

]

},

{

"cell_type": "markdown",

"metadata": {

"deletable": false,

"editable": false,

"heading_collapsed": true,

"run_control": {

"frozen": true

}

},

"source": [

"#### Hint"

]

},

{

"cell_type": "markdown",

"metadata": {

"deletable": false,

"editable": false,

"hidden": true,

"run_control": {

"frozen": true

}

},

"source": [

"To do you one iteration of bisection search, you should first compute the point `c = (x_low+x_high)/2` , then compute `f3 = (c-1)*(c-3)`.\n",

"\n",

"Then, you can either use a double `if` statement, splitting into two cases (`f3 < 0` and `f3 > 0`) and for each of these working out what values to swap (e.g. if f3 < 0 and f1 < 0, swap xlow and c), OR you can check four cases (i.e. check the cases: `if f3 < 0 and f1 < 0` ; `if f3 < 0 and f2 < 0`, `if f3 > 0 and f1 > 0`, and `if f3 > 0 and f2 > 0`). If you are clever, you can reduce this to just checking two conditions!"

]

},

{

"cell_type": "markdown",

"metadata": {},

"source": [

"### Task d)"

]

},

{

"cell_type": "markdown",

"metadata": {

"deletable": false,

"editable": false,

"run_control": {

"frozen": true

}

},

"source": [

"So far, we have only considered the function $f(x)=(x−1)(x−3)$ but we can, of course, apply the algorithm to other functions. Check if the program works by testing on the function $g(x)=x^2−2$. The only variables you need to change are `f1`, `f2` and `f3=f(c)`. \n",

"\n",

"\n",

"Example run:\n",

"```\n",

"Lower limit of interval: 0\n",

"Upper limit of interval: 4\n",

"There is a zero between 0 and 2.0.\n",

" \n",

"Lower limit of interval: 0\n",

"Upper limit of interval: 2\n",

"There is a zero between 1.0 and 2.0.\n",

" \n",

"Lower limit of interval: 1\n",

"Upper limit of interval: 2\n",

"There is a zero between 1.0 and 1.5.\n",

" \n",

"Lower limit of interval: 1\n",

"Upper limit of interval: 1.5\n",

"There is a zero between 1.25 and 1.5.\n",

".\n",

".\n",

".\n",

"Lower limit of interval: 1.4140625\n",

"Upper limit of interval: 1.421875\n",

"There is a zero between 1.4140625 and 1.41796875.\n",

"```\n",

"Observe that the zero of g in this interval is x=2√≈1.4142, which lies between 1.414 and 1.418. \n",

"\n",

"**Write code in the block below**"

]

},

{

"cell_type": "code",

"execution_count": null,

"metadata": {},

"outputs": [],

"source": [

"# Write code for task d) here\n",

"\n",

"\n",

"\n"

]

}

],

"metadata": {

"kernelspec": {

"display_name": "Python 3",

"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.7.4"

}

},

"nbformat": 4,

"nbformat_minor": 2

}

%% Cell type:markdown id: tags:

# Bisection search

**Learning goals:**

- Conditional statements

- Pseudocode

**Starting Out with Python:**

- Ch. 3.4

%% Cell type:markdown id: tags:

### Bisection search theory

%% Cell type:markdown id: tags:

Bisection search is a basic algorithm for finding zeroes of [continuous functions](https://en.wikipedia.org/wiki/Continuous_function). Given a function f we first look for an interval $[a,b]$ such that either $f(a) <0\textrm{and}f(b)> 0,$ or $f(a) > 0 \textrm{ and } f(b) < 0.$

Then, since $f$ is continuous, there must be a solution point $x$ in $[a,b]$ such that $f(x)=0.$

To make the interval tighter around $x$, we check the value at the midpoint $c = \frac{a + b}{2}.$

For simplicity, let us assume that $f(a)<0,$and$f(b)>0.$ If the opposite is true, we can just switch the roles of $a$ and $b$ in the following.

If $f(c)<0$thenwecanexchange$a$for$c$andstartoverwiththesmallerinterval$[c,b]$.Likewise,if$f(c)>0$ then we can exchange $b$ for $c$ and start over with $[a,c]$.

In both cases, we end up with an interval of length $\frac{b-a}{2},$ half of the original search interval. Crucially, $f$ has values of opposite signs at the endpoints of this interval, so the interval still contains an $x$ such that $f(x)=0.$

We can summarize the algorithm in the following pseudocode:

- 1: Pick a starting interval $[a, b]$

- 2: If $f(a)$ and $f(b)$ have the same sign, stop the program and report an error with the starting interval.

- 4: Replace either $a$ or $b$ with $c$ according to the rules above.

- 5: If the interval is small enough, stop. Otherwise, start over from step 3 with the smaller interval.

In this exercise, you will use `if-elif-else` statements to answer input from the user. Consider the use of bisection search to find a zero of the function $f(x)=(x−1)(x−3)$ with starting interval $[-1,2]$.

%% Cell type:markdown id: tags:

### Task a)

%% Cell type:markdown id: tags:

Make a program that asks the user which number the method converges to. If the user answers 1, *print*`Great! Correct answer `. Otherwise, *print*`Wrong.`

Example run:

```

Which number does the method converge to? 1

Great! Correct answer.

Which number does the method converge to? 3

Wrong.

```

**Write code in the block below**

%% Cell type:code id: tags:

``` python

# write code for task a) here

```

%% Cell type:markdown id: tags:

### Task b)

%% Cell type:markdown id: tags:

The two zeroes of $f$ are clearly 1 and 3. Make a program that asks the user for a lower and upper limit for the starting interval and checks if the interval contains none, one or both of the zeroes.

Example run:

```

Lower limit of interval: -1000

Upper limit of interval: 0.5

There is no zero between -1000 and 0.5.

Lower limit of interval: 2

Upper limit of interval: 4

There is one zero between 2 and 4.

Lower limit of interval: 0

Upper limit of interval: 3.5

There are two zeroes between 0 and 3.5.

```

**Write code in the block below**

%% Cell type:code id: tags:

``` python

# Write code for task b) here

```

%% Cell type:markdown id: tags:

### Task c)

%% Cell type:markdown id: tags:

We will now work toward making an implementation of bisection search.

Make a program that asks the user for a lower and upper limit for the starting interval. Make a variable $\mathtt{f1} = (x_{\mathrm{low}}-1)(x_{\mathrm{low}}-3)$ and a variable $\mathtt{f2} = (x_{\mathrm{high}}-1)(x_{\mathrm{high}}-3)$ where $x_{low}$ is the lower limit and $x_{high}$ the upper limit.

If `f1*f2 < 0`, the interval is a valid starting interval. If this is the case, do **one** iteration of bisection search (i.e. points 3 and 4 of the pseudoalgorithm) and print the new interval. Otherwise, print `Invalid starting interval`.

%% Cell type:markdown id: tags:

Run example:

```

Lower limit of interval: 2

Upper limit of interval: 5

There is a zero between 2 and 3.5.

Lower limit of interval: 0

Upper limit of interval: 5

Invalid starting interval.

```

**Write code in the block below**

%% Cell type:code id: tags:

``` python

# Write code for task c) here

```

%% Cell type:markdown id: tags:

#### Hint

%% Cell type:markdown id: tags:

To do you one iteration of bisection search, you should first compute the point `c = (x_low+x_high)/2` , then compute `f3 = (c-1)*(c-3)`.

Then, you can either use a double `if` statement, splitting into two cases (`f3 < 0` and `f3 > 0`) and for each of these working out what values to swap (e.g. if f3 <0andf1<0,swapxlowandc),ORyoucancheckfourcases(i.e.checkthecases:`iff3<0andf1<0`;`iff3<0andf2<0`,`iff3> 0 and f1 > 0`, and `if f3 > 0 and f2 > 0`). If you are clever, you can reduce this to just checking two conditions!

%% Cell type:markdown id: tags:

### Task d)

%% Cell type:markdown id: tags:

So far, we have only considered the function $f(x)=(x−1)(x−3)$ but we can, of course, apply the algorithm to other functions. Check if the program works by testing on the function $g(x)=x^2−2$. The only variables you need to change are `f1`, `f2` and `f3=f(c)`.

Example run:

```

Lower limit of interval: 0

Upper limit of interval: 4

There is a zero between 0 and 2.0.

Lower limit of interval: 0

Upper limit of interval: 2

There is a zero between 1.0 and 2.0.

Lower limit of interval: 1

Upper limit of interval: 2

There is a zero between 1.0 and 1.5.

Lower limit of interval: 1

Upper limit of interval: 1.5

There is a zero between 1.25 and 1.5.

.

.

.

Lower limit of interval: 1.4140625

Upper limit of interval: 1.421875

There is a zero between 1.4140625 and 1.41796875.

```

Observe that the zero of g in this interval is x=2√≈1.4142, which lies between 1.414 and 1.418.

"- Ch 3 - Decision Structures and Boolean Logic\n",

"\n",

"**Additional theory in drop-down menus in the mandatory numerics exercises is part of the curriculum.**\n",

"\n",

" \n",

"\n",

"## Approval:\n",

"\n",

"You must do the two mandatory exercises for TDT4127 (Programming and Numerics), in addition to three exercises of your own choice from the table of regular programming exercises. \n",

"\n",

"Tasks that are a little extra difficult are marked with a star. Tasks that go beyond what has been lectured are marked with two stars.\n",

"\n",

"All assignments (you have done) must be demonstrated to a learning assistant in person and uploaded as .py or .ipynb file to Blackboard. Good luck!\n",

**Additional theory in drop-down menus in the mandatory numerics exercises is part of the curriculum.**

## Approval:

You must do the two mandatory exercises for TDT4127 (Programming and Numerics), in addition to three exercises of your own choice from the table of regular programming exercises.

Tasks that are a little extra difficult are marked with a star. Tasks that go beyond what has been lectured are marked with two stars.

All assignments (you have done) must be demonstrated to a learning assistant in person and uploaded as .py or .ipynb file to Blackboard. Good luck!