From: Tim Hunter Date: 2006-03-31T09:13:43+09:00 Subject: Re: Very interesting Float comparison! Ryan Allen wrote: > Hi Guys (and Gals!) > > This is my first post on the list, so Hello! > > Something very strange is happening (as far as I can tell) with a float > comparison; here is the code in question: > > ("55.59".to_f / 100) == 0.5559 # returns false > > However: > > "55.59".to_f / 100 # returns Float 0.5559 > 0.5559 # returns Float 0.5559 > 0.5559 == 0.5559 # returns true > > And more!: > > ("55.5".to_f / 100) == 0.555 # returns true > ("55.53".to_f / 100) == 0.5553 # returns true > ("55.56".to_f / 100) == 0.5556 # returns true > ("55.58".to_f / 100) == 0.5558 # returns true > ("55.59".to_f / 100) == 0.5559 # returns false !! > ("44.59".to_f / 100) == 0.4449 # returns true !! > ("44.59".to_f / 100) == 0.4449 # returns false !!!! > > It doesn't seem to like .59's... What did .59 ever do? > > I picked this up while writing a unit test, I've run this code in irb > and I'm not sure what's going on... > > Can anyone shed some light on this? > > I'm using ruby 1.8.4 (2005-12-24) [powerpc-darwin8.5.0] > > Cheers, > Ryan. > > The comparison of floating-point numbers is notoriously problematic throughout all computing, not just Ruby. Here's a good description of the problem: http://en.wikipedia.org/wiki/Floating_point. You can also find many discussions of this same "problem" by searching the archives of this list. Typically you don't test two floating-point numbers for equality, you test that the difference is very small. This is what the assert_in_delta assertion is for.