CSC 325 Grinnell College Fall, 2008
 
Databases and Web Application Design
 

Laboratory Exercise on Functions, Conditionals, and Iteration in PHP

This laboratory exercise provides practice with several elements of the PHP programming language.

Example: A Family-Size Simulation

To illustrate elements of conditionals and iteration in PHP, consider the following:

Problem:

A couple decides that they want to raise at least one boy and one girl. They decide to keep having children until they have one child of each gender, and then stop having children. Assume that having a boy or a girl is equally likely, and assume that the gender of one child has no influence on the gender of the next. Determine the number of children that the couple might expect to have.

Program family-size.php gives the results of a simulation of the family size for 20 couples.

Steps for this Lab

  1. Run this program a few times and observe the output.

The family-size.php HTML/PHP Script

Skipping over the page header, the main part of this script is shown below, where $numberCouples stores the value 20 (the number of couples to be considered).

    
    <php
    $numberCouples = 20;
    ?>
    <table>
    <tr>
       <th>Couple
       <th>Boys
       <th>Girls
       <th>Total
    </tr>
    
    <?php
    for ($couple = 1; $couple <= $numberCouples; $couple++) {
      $boys = 0;
      $girls = 0;
      while (($boys == 0) || ($girls == 0)) {
        // rand returns a random integer, in this case between 0 and 1
        // the program interprets 0 as a boy, 1 as a girl
        if (rand(0, 1) == 0)
          $boys++;
        else
          $girls++;
      }
    ?>
      <tr>
         <td>Couple <?php echo $couple; ?>
         <td align=center><?php echo $boys;  ?>
         <td align=center><?php echo $girls; ?>
         <td align=center><?php echo $boys + $girls; ?>
      </tr>
    <?php
    }
    ?>

    </table>

Notes:

More Steps for this Lab

  1. Copy ~walker/public_html/courses/325.fa08/labs/family-size.php to your public_html directory.

  2. Expand the family-size.php program to compute the total number of boys and girls for the 20 couples, and print this as a new row at the bottom of the table.

  3. Compute the average number of boys and girls for the 20 couples and the average number of children for the 20 couples, printing this as a final row in the table.

Finding Square Roots

We consider the problem of finding the square root of a non-negative number.

For a number p, let f(x) = x2 - p. Then f(x) is a continuous function, and finding the square root of p is a special case of finding values of x, called roots, for which f(x) = 0.

We now consider two algorithms for finding the roots of a continuous (or differentiable) function:

The Bisection Method

Given a continuous function f, we want to approximate a value r where f(r)=0. While this can be a difficult problem in general, suppose that we can guess two points a and b (perhaps from a graph) where f(a) and f(b) have opposite signs. The four possible cases are shown below:

4 Cases for the Bisection Method

Given a and b, we know that a root r must lie between them, since f(a) and f(b) have opposite signs. Thus, we know that r must lie in the interval [a, b]. In one step, we can cut this interval in half as follows. If f(a) and f(m) have opposite signs, then r must lie in the interval [a, m]; otherwise, r must lie in the interval [m, b].

To apply this to finding the square root of the positive number p, we must find an initial interval that contains the desired square root. One simple rule for finding such an interval follows:

Lab Steps on the Bisection Method

  1. Write a Web page root-1.html, in your public_html directory, with a form asking for a non-negative number. Upon clicking submit, the form should call page square-root-1.php that applies the Bisection Method to the number to find the square root of the entered number.

  2. Restructure step 5, so that the computation is done in a user-defined function. That is:

    You may want to review the class example scripts and the textbook regarding how to define PHP functions.

Newton's Method

Newton's method is remarkably efficient for typical functions, but it has some limitations:

However, when it works, Newton's method produces very accurate approximates to roots in a very short amount of time.

The following description is a slightly-edited version of what appears in Section 5.1 of Problems for Computer Solutions Using Basic by Henry M. Walker, Winthrop Publishers, 1980.

The following algorithm, which is credited to Newton, can often be used to approximate the roots of a differentiable function efficiently and accurately. In the algorithm we begin by making a guess x0 for the root of a function f(x). The algorithm then gives us a "closer" approximation x1 to the root. We can then use x1 as our guess, apply the algorithm again, and get a still better guess. This process continues until we are satisfied with our approximation.

The key, therefore, is to decide how to improve a guess a. Here we observe that the tangent line to a cure is usually a good approximation to the curve "near" the point of tangency. Thus, if the point of tangency is near the root, the tangent line will cross the horizontal coordinate axis near the point where the curve crosses the axis.

We look at the equation of the tangent line to the curve y = f(x) at the point where x=a, The point of tangency is ((a, f(a)) and the slope at this point is f'(a), so by the point-slope form of a line, the equation of the tangent is given by

y - y0 = m(x - x0)
or
y - f(a) = f'(a)(x - a)

This tangent crosses the x-axis at a point (b, 0), and since this point is on the tangent, we must have

0 - f(a) = f'(a)(b - a)
or
b = a - f(a) / f'(a)

The geometry of this process is shown in the following diagram.

Approximating a Root by a Tangent

We can now describe Newton's method more precisely.

First, choose an initial approximation, call it x0, for the root (this may be only a blind guess or it may be based on some knowledge, such as a rough sketch of the graph). Secondly, construct a sequence of numbers:

x1 = x0 - f(x0)/ f'(x0)
x2 = x1 - f(x1)/ f'(x1)
x3 = x2 - f(x2)/ f'(x2)

Because the above formula gives the x-intercept of the tangent to the curve corresponding to x = a, the above iterative process can be graphically described by the dotted line in the following graph.

Approximating a Root by a Tangent

The general form of Newton's method can be written:

  1. x0 arbitrary
  2. xn+1 = xn - f(xn)/ f'(xn); (n = 0, 1, 2, ...)
  3. stop when you are close to the root.

We expect that for reasonably shaped curves, the xn values approach the actual root as n increases.

Notes:

  1. When do you stop the process? There are various ways of deciding when you are close to the root. None of them are completely satisfactory. The procedure that we will use is to choose some measure on the error err that we are willing to tolerate, for example err = 10-6. We then continue the iteration process until |f(xn)| ≤ err

    This procedure cannot give acceptable results for every function, because it states that x = 1 is an acceptable approximation to the root x = 0 of the function f(x) = err * x.

  2. The following figure indicates a situation where Newton's method fails completely because of an unfortunate initial guess of either x = a or x = b.
    A Case wheter Newton's Method Fails

Lab Steps on Newton's Method

  1. Write a Web page root-3.html, in your public_html directory, with a form asking for a non-negative number. Upon clicking submit, the form should call page square-root-3.php that applies Newton's method to the number to find its square root.

  2. Reorganize your Newton's Method program, so the computation of Newton's Method is done is a separate function, located in a separate file:

    You may want to review the class example scripts and the textbook regarding how to define PHP functions and separate functions into separate files.

Additional Step for this Lab

  1. Run your square root approximations using both the Bisection Method and Newton's Method for several values.

    1. Discuss briefly the accuracy of both methods. (For example, check the results against a calculator or the Scheme function.)
    2. Compare the efficiency of the two algorithms; how many iterations are needed for each algorithm?

Work to be Turned In


This document is available on the World Wide Web as

     http://www.cs.grinnell.edu/~walker/courses/325.fa08/lab-cond-iteration.shtml

created 10 August 1998
last revised 23 September 2008
Valid HTML 4.01! Valid CSS!
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.