On Fri, 22 Jun 2007 04:25:04 +0900, “[email protected]”

[email protected] wrote:

Dear friends, today I have stumbled into a really weird problem. Try

typing this on irb:

14.95 * 0.6 == 8.97

Ruby says it’s false!

This happens in all languages that use floating point to represent

decimal numbers (you will get precisely the same result in C or

Javascript or Perl, for instance). Floating-point arithmetic is only

approximate, so the result does not *exactly* equal 8.97, even though it

is very close.

Because of this, when using floating-point arithmetic, testing for exact

equality is impractical. The best you can do is test whether the result

is within some interval (epsilon) of the expected result:

( ( 14.95 * 0.6 ) - 8.97 ).abs < 1e-6

(Here, we’ve chosen 1e-6 as our epsilon, which is arbitrary but probably

“small enough” in this case. For mathematically intensive code, you may

need to be more careful.)

Although floating-point is the default for Ruby, you do have the option

of using a different representation of numbers for which arithmetic is

exact, although it will not be as fast. One such option is the Rational

class in Ruby’s standard library, which represents numbers as fractions

rather than floating-point numbers.

-mental