Computer Science I / Program Design for Scientific or Engineering Tasks
Practice question · Put in order

Order the steps of diagnosing and repairing a failing exact-equality test on floating-point values.

Hints
  1. The diagnosis has to come before the repair, and the repair needs a number chosen for this problem.
  2. You cannot write the tolerance comparison until you have decided what tolerance means here.
Show the answer
  1. Notice that a test fails although the two values print identically
  2. Print the values to full precision and see that they differ in the last digits
  3. Choose a tolerance small compared with the quantities being compared
  4. Replace the equality test with a check that the absolute difference is below that tolerance
  5. Re-run and confirm the test now passes for the right reason
Why

The full-precision printout is what turns a baffling failure into an understood one, and the tolerance must be sized to the quantities before the comparison can be written. Choosing a tolerance blindly, say 1e-15 on values of order a million, reproduces the original failure with extra steps.

Read the lesson: Program Design for Scientific or Engineering Tasks →

Practise Program Design for Scientific or Engineering Tasks

The app has 8 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.

More questions on Program Design for Scientific or Engineering Tasks