Floating-point numbers are not suitable for exact comparison. Often, two numbers that should be equal are actually slightly different. The Ruby interpreter can make seemingly nonsensical assertions when floating-point numbers are involved:
1.8 + 0.1 # => 1.9 1.8 + 0.1 == 1.9 # => false 1.8 + 0.1 > 1.9 # => true
You want to do comparison operations approximately, so that floating-point numbers infintesimally close together can be treated equally.
You can avoid this problem altogether by using
BigDecimal numbers instead of floats (see
BigDecimal numbers are completely precise,
and work as well as as floats for representing numbers that are
relatively small and have few decimal places: everyday numbers like
the prices of fruits. But math on
BigDecimal numbers is much slower than math
on floats. Databases have native support for floating-point numbers,
but not for
floating-point numbers are simpler to create (simply type
10.2 in an interactive Ruby shell to get a
BigDecimals can't totally replace floats,
and when you use floats it would be nice not to have to worry about
tiny differences between numbers when doing comparisons.
But how tiny is "tiny"? How large can the difference be between two numbers before they should stop being considered equal? As numbers get larger, so does the range of floating-point values that can reasonably be expected to model that number. 1.1 is probably ...