Discovering Computer Science by Jessen Havill

Discovering Computer Science by Jessen Havill

Author:Jessen Havill
Language: eng
Format: epub, pdf
Publisher: CRC Press
Published: 2018-10-03T16:00:00+00:00


assert getWordCounts(text, 'the', 20) == 4 / 15

assert getWordCounts(text, 'spleen', 20) == 1 / 15

print('Passed all tests of getWordCounts!')

Reflection 7.13 Why did we use 4 / 15 and 1 / 15 in the tests above instead of something like 0.267 and 0.067?

Using these floating point approximations of 4/15 and 1/15 would cause the assertions to fail. For example, try this:

>>> assert 4 / 15 == 0.267 # fails

In general, you should never test for equality between floating point numbers. There are two reasons for this. First, the value you use may not accurately represent the correct value that you are testing against. This was the case above. To get assert 4 / 15 == 0.267 to pass, you would have to add a lot more digits to the right of the decimal point (e.g., 0.26666 ··· 66). But, even then, the number of digits in the value of 4 / 15 may depend on your specific computer system, so even using more digits is a bad idea. Second, as we discussed in Sections 2.2 and 4.4, floating point numbers have finite precision and are therefore approximations. For example, consider the following example from Section 4.4.

sum = 0

for index in range(1000000):

sum = sum + 0.0001

assert sum == 100.0

This loop adds one ten-thousandths one million times, so the answer should be one hundred, as reflected in the assert statement. However, the assert fails because the value of sum is actually slightly greater than 100 due to rounding errors. To deal with this inconvenience, we should always test floating point values within a range instead. For example, the assert statement above should be replaced by

assert sum > 99.99 and sum < 100.01

or

assert sum > 99.99999 and sum < 100.00001

The size of the range that you test will depend on the accuracy that is necessary in your particular application.

Let’s apply this idea to the familiar volumeSphere function:

def volumeSphere(radius):

return (4 / 3) * math.pi * (radius ** 3)

To generate some test cases for this function, we would figure out what the answers should be for a variety of different values of radius and then write assert statements for each of these test cases. For example, the volume of a sphere with radius 10 is about 4188.79. So our assert statement should look something like

assert volumeSphere(10) > 4188.789 and volumeSphere(10) < 4188.791



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.