Page 161 - Learn To Program With Scratch
P. 161
comParing DecimaL numBerS
Special care must be taken when using the equal operator to compare decimal
numbers . Because of the way these numbers are stored inside the computer,
the comparison may sometimes be imprecise . Consider the command blocks
shown here:
The result of dividing 1 by 3 is 0 .3333… with the sequence of 3s repeat-
ing forever . Since the computer uses a fixed amount of space to store the result,
the fraction 1/3 cannot be exactly stored by the computer . Although Scratch
tells you that the result of the division is 0 .33 at u, the actual result is saved
internally with much higher precision . Therefore, the results of the first two com-
parisons in the figure (v and w) evaluate to false .
Depending on your programming situation, you may be able to prevent
this type of error by using one of the following approaches:
• Use the less than (<) and greater than (>) operators instead of the equals
operator (=) when possible .
• Use the round block to round the two numbers you need to compare, and
then compare the rounded numbers for equality .
• Test the absolute difference between the two values you are comparing . For
example, instead of testing if x equals y, we can check to see if the absolute
difference between x and y is within an acceptable tolerance by using a
block similar to this one:
Depending on the accuracy of the numbers and the method of calcu-
lating these numbers, this method may be sufficient for your purpose .
Making Decisions 139
www.it-ebooks.info

