Problem Set 4

| categories: Problem Sets

Due: Friday 4 November before lab.

In this assignment you'll get some experience with the strangeness of floating point arithmetic. Feel free to run these programs on your computer.

Problem 1. Why won't it stop? (25 points)

The following program never prints "done", in fact it never terminates. Why not?

#include 

void main() {
  double a = 0.0;

  printf("start\n");
  while (a != 1.0) {
    a += 0.1;
  }
  printf("done\n");
}

Problem 2. Stop that! (25 points)

Show how we should modify the code above using the fabs function to properly quit with variable a near 1.

Problem 3. Breaking the law. (25 points)

We know from algebra that the only solution to the equation 1 + epsilon = 1 is epsilon = 0. But our computers don't work that way. The following code determines the largest value of epsilon that breaks the law. Explain what it the code is doing, and why this value of epsilon is the largest.

#include 

void main() {
  float eps = 1.0f;
  while (1) {
    float op = 1.0f + eps;
    if (op == 1.0f) {
      break;
    }
    eps *= 0.5;
  }
  printf("eps = %g\n", eps);
}

Problem 4. Huge law breakers. (25 points)

Show how you would modify the code above to find the smallest double precision number, x such that x + 1 == x.