October 2006
Intermediate to advanced
888 pages
16h 55m
English
It is a sad fact of life that computers do not represent floating point values exactly. The following code fragment, in a perfect world, would print “yes”; on every architecture we have tried, it will print “no” instead:
x = 1000001.0/0.003 y = 0.003*x if y == 1000001.0 puts "yes" else puts "no" end
The reason, of course, is that a floating point number is stored in some finite number of bits; and no finite number of bits is adequate to store a repeating decimal with an infinite number of digits.
Because of this inherent inaccuracy in floating point comparisons, we may find ourselves in situations (like the one we just saw) in which the values we are comparing are the same for all practical purposes, but ...
Read now
Unlock full access