Skip to main content

Section 7.5 Testing Floating Point Numbers

There is an important and potentially confusing aspect of writing conditionals that involve floating point numbers. Recall that floating point numbers are only approximations of real numbers. This means that two floating point numbers that we expect to be equal may not be exactly equal. For example, the result of this computation might be surprising:
Listing 7.5.1.
The calculation that produces b doesn’t end up making exactly 5.03 due to the way floating point numbers are represented in memory. So, the comparison a == b return false. We can ask the compiler to warn us about this, which is what this second version of the same program does:
Listing 7.5.2.
To properly compare floating point numbers, we need to check if they are "close enough" rather than exactly equal. This is typically done by checking if the absolute difference between the two numbers is less than a small threshold value (often called epsilon). Here is an example of how to do this:
Listing 7.5.3.
The exact value of epsilon we should use depends on the precision we require and on the magnitude of the numbers being compared. (The accuracy of floating point numbers is limited to a certain number of digits, not a certain number of decimal places.)
Although this is awkward, it should also be relatively rare. If you expect a floating point number to be exactly equal to a whole number, you can use an integer comparison instead. And you can safely use less than or greater than comparisons with doubles. You will not get a warning about checking something like temp <= 212.0 even though you are comparing two doubles. It is only checking to see if values are exactly == or != that is problematic.

Checkpoint 7.5.1.

We want to check if x and y are close enough to be considered equal. We will consider within 0.01 to be β€œclose enough”. Build the code to do this check. You will not need all of the blocks
You have attempted of activities on this page.