CS1109 Programming and Web Development, 2012-2013

© Derek Bridge 2013

University College Cork

Aims:

- to recognise a classic use of a
`while`

-loop for unbounded repetition

- It is not possible to store all real numbers exactly using floating-point representation, which uses a finite number of bits
- E.g. in decimal 1/3 = 0.33333…
- E.g. the decimal number 0.1 becomes an infinitely recurring number in binary (see this FAQ or this guide)
- The floating-point representation will introduce a small truncation error
- One consequence is our programs' results may be off slightly: how to analyse, and minimise, these errors is the subject of modules on numerical analysis
- Another consequence is, when using floats, you should never expect one value you calculate to exactly equal another
**Class exercise:**What do you think the output will be:

`if ( sqrt(2) * sqrt(2) == 2 )`

{

echo 'Yes';

}

- In the previous lecture, we computed the square root of a non-negative integer by counting the number of successive odd numbers we needed to subtract to reach zero
- In this lecture, we take another approach to computing square roots: by repeatedly 'guessing'
- So we use the following
form. The second text field will be explained in the lecture:
<form action="root.php" method="get"> <input type="text" name="number" /> <input type="text" name="epsilon" /> <input type="submit" /> </form>

In the rest of the lecture we'll write`root.php`

- We'll keep two numbers,
`$lo`

and`$hi`

- Initially,
`$lo`

will 0 and`$hi`

will be the number the user supplies and`$guess`

will be the number the user supplies - If
`$guess`

is 'good enough', we will stop - If not,
- if
`$guess`

was too big, our next guess can lie halfway between`$lo`

and`$guess`

- if
`$guess`

was too small, our next guess can lie halfway between`$guess`

and`$hi`

- if
**Class exercise:**Why will we use a`while`

-loop for this, rather than a`for`

-loop?