CS 415, Section 001 | Sonoma State University | Spring, 2023 |
Algorithm Analysis
|
||
Instructor: Henry M. Walker
Lecturer, Sonoma State University |
Although much of this course is well developed, some details can be
expected to evolve as the semester progresses.
Any changes in course details will be announced promptly during class.
This laboratory exercise explores some practical consequences of the representation of data in program processing.
Recall from your prior work in C/C++ that constants variables INT_MIN and INT_MAX in C/C++ contain the smallest and largest int values available in C/C++.
Suppose i
and j
are two non-negative
integers, and a program is supposed to find their average (as an
integer). (In case the arithmetic average is a real number ending
in .5, then the average may be rounded either up or down. Thus, the
actual average 7.5 of 6 and 9 may be rounded to either 7 or 8.)
Five approaches are proposed to find this average:
avg1 = (i + j) / 2;
avg2 = i/2 + j/2;
avg3 = (i+1)/2 + j/2;
avg4 = i/2 + (j+1)/2;
avg5 = (i+1)/2 + (j+1)/2;
i
and j
? Explain.
i
and j
may be any
integers—positive, negative, or zero. In this general case,
which, if any, of these approachs will work reliably for all values
of i
and j
? Explain.
Consider the program integer-average.c.
Consider program arithmetic-series.c
Our discussions of the representation of real numbers (doubles and floats) have identified at least three factors that can cause errors in processing—particularly if the errors can accumulate as processing continues.
Be sure to take these potential troubles into account in answering Steps 4 and 5.
Given that start < end
, suppose a loop is to
begin at start
and finish at (or near)
end
in exactly n+1
iterations. Within
this loop, suppose the control variable will increase by a
computed value increment = (end-start)/n
with each iteration.
Two loop structures are proposed:
// approach 1 increment = (end - start)/n; for (i = 0; i <= n; i++){ value = start + i * increment; /* processing for value */ }
// approach 2 value = start; increment = (end - start)/n; while (value <= end) { /* processing for value */ value += increment; }
Although the first approach requires somewhat more arithmetic within the loop than the second, it likely will provide better accuracy. Identify two distinct reasons why the first approach should be preferred over the second.
Suppose y = f(x)
is a function that decreases
from x=a
to x=b
, on the interval
[a, b]
, with a < b
.
Throughout this interval, assume f(x)>0
, and
assume the Trapezoidal Rule were to be used to approximate the
area under y = f(x)
on the interval
[a, b]
.
a
and go
toward b
or begin at b
and go
toward a
, or is either order fine? Explain.
created 31 March 2022 expanded 24 July 2022 expanded 3 January 2023 |
![]() ![]() |
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu. |
![]() |
Copyright © 2011-2022
by Henry M. Walker.
|