As usual, create two directories for today's class. Create a
directory called lecture19
under activities, and
a directory called lab19
under labs.
For loops work great for when you know exactly how many times you want something to execute. However, it is often times the case that we don't know that critical piece of information. We know when we want to stop, but we don't know how long that process might take.
While loops are essentially a conditional statement that executes while some specific condition continues to hold. This allows us to create a loop that executes for some finite, but undetermined amount of time.
Create a file (using Emacs) called input_average.py
in
your lecture19 directory. In this file, use a while loop to continually
read in positive integers from user input until a -1
value is input by the user.
As the user types in integers, you should use the same accumulator pattern we used in our for loops to compute the total sum of all positive grades entered by the user. You will also need to keep track of how many grades were actually entered.
When you finish your program, go to inquire, and compute your quiz average with your program. Does the total match up with what inquire reports?
As you saw in class today, we can use loops to get decent estimates of slightly complicated mathematical operations, such as log. Another difficult to compute operation is square root. One of the earliest known methods for approximating a square root was in use by the Babylonians in the 5th century B.C.E.
The method for approximating the square root is very similar to the log example shown in class. To find the square root of n, we start out with s, which is our current approximation for the square root of n. We can iteratively compute a new value:
We can continue to perform this computation until our current value s2 is close enough to n that the difference is negligible.
Create a file babylonian_roots.py
in your lab19
directory. Create a function babylonian_approximation
that, when given some positive integer n,
returns an approximation of the square root of n.
Make sure you test your program well. How many test cases do you need? Include your test cases in your program file. Comment them appropriately.
When you have finished, create a tar file of your lab19
directory. To create a tar file, execute the following commands:
cd ~/cs120/labs tar czvf lab19.tgz lab19/
To submit your activity, go to cseval.roanoke.edu. You should
see an available assignment called Lab Assignment 19
. Only
one of your pair should submit your activity. Make sure both partners
are listed in the header of your files.
Do not forget to email your partner today's files!