keyboard

CoSc2030: Computer Science II

Fall Semester 2007
Instructor: Dr. Thomas Bailey

Lab 2: Numeric Errors

We usually say that computers are better than people at "number crunching". But as this lab demonstrates, there are several issues that programmers need to take into account when performing computer arithmetic. During the lab lecture we talked about the problem of numeric overflow and precision limitations of floating point number representation. This lab gives you a chance to investigate the problem in context of several calculations.

Lab Assignment:

  1. Write a function that computes the sum of consecutive integers of type short: sum formula. Experiment with several values for the upper limit (n in the formula). Detect the overflow by outputing the results to the console and report the value of n that produces the overflow. (Hint: try values around 250).
  2. Write a function that computes the sum of consecutive integers of type long (see formula above). Again, test different values for the upper limit and report the value of n that causes an overflow.
  3. Write a routine that computes the factorial function: factorial formula Use float to store the result of the computation, and experiment with several values for n. How can you detect an overflow in this case? You might find it helpful to consult the Visual Studio online help. (Hint: unlike integer types, floating point numbers have a special bit pattern reserved for infinity, so a float variable overflows when it stops being finite.)
  4. Write a routine that computes the factorial function as above, but use a double to store the result. What value of n causes an overflow?
  5. Here is an example of "strange" floating point number behavior: implement the function that computes . Try it out with different values of n and experiment with float and double as the data types to store the result. (Try computing both sum = 1 and sum = -1) Can you explain the error?
  6. And how about this puzzle: execute the following piece of code, and explain where and why the numeric error occurs:
    for (float i = 3.4; i < 4.4; i += 0.2) {   cout << "i = " << i << endl;}
  7. Now change the type of variable i in the code fragment above to type double. Explain the effect.

Turn In:

Upload your source code in a file Lab2NumericErrors.cpp with the implementation of the requested functions. Include your answers to the above questions as comments in the code along with your name

<< CoSc2030 Home
Copyright © 2005 Thomas Bailey