From: Nasir Khan Date: 2007-06-22T04:50:58+09:00 Subject: Re: Ruby doesn't know how to multiply ------=_Part_116379_3500735.1182455453086 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline And if you are using test/unit then use the assertion method assert_in_delta() - nasir On 6/21/07, MenTaLguY wrote: > > On Fri, 22 Jun 2007 04:25:04 +0900, "rjprado@gmail.com" > 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 > > > ------=_Part_116379_3500735.1182455453086--