From: Rob Biedenharn Date: 2008-02-08T07:57:42+09:00 Subject: Re: BigDecimal.new('15.25') == 15.25, false ?? On Feb 7, 2008, at 5:26 PM, Henry Jones wrote: > Hi, > > I was writing some unit tests when I ran into some troubles.. In the > end > I found out the problem : > > BigDecimal.new('15.25') == 15.25 > > returns false !! > > BigDecimal.new('15.25').to_f == 15.25.to_f also returns false. > > Substracting both values returns 1.7763... e-015 > > This is on ruby 1.8.6, Win32. > > I'm a comp. engineer, so I know it's ultimately related to the binary > value of 15.25 which cannot be precisely represented (without an > infinite number of bits) , but I'm still amazed that such a simple > comparison with a literal value should fail... 15.25 in decimal is exactly 1111.01 in binary Seems like a finite number of bits to me ;-) However, the construction of 15.25 as a literal is likely something roughly (1*10^1 + 5*10^0) + (2*10^-1 + 5*10^-2) and those intermediate fractional terms are problematic. Hey, this is Ruby! Roll your own with === irb> class Float irb> def ===(other,eps=0.000000001) irb> (self - other.to_f).abs < eps irb> end irb> end => nil irb> require 'bigdecimal' => true irb> 15.25 == BigDecimal.new("15.25") => false irb> 15.25 === BigDecimal.new("15.25") => true Of course, you'd have to add a similar BigDecimal#=== to get symmetry. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com