From: Gavin Kistner Date: 2005-11-28T07:52:18+09:00 Subject: Re: floating point subtraction question On Nov 27, 2005, at 3:41 PM, Nicholas Rahn wrote: > I'm a bit confused with some simple floating point arithmetic: > > % ruby -e 'puts "#{(1.2 - 1.0) == 0.2}"' > false > > % ruby -e 'puts "#{(1.5 - 1.0) == 0.5}"' > true Slim:~ gavinkistner$ irb irb(main):001:0> 1.2-1.0 => 0.2 irb(main):002:0> (1.2-1.0)==0.2 => false irb(main):003:0> "%.31f" % [1.2-1.0] => "0.1999999999999999555910790149937" irb(main):004:0> "%.31f" % [0.2] => "0.2000000000000000111022302462516" irb(main):005:0> "%.31f" % [1.2] => "1.1999999999999999555910790149937" Because many digits cannot be precisely represented as powers of 2. For more info, try a plethora of online resources on floating point math, such as: http://en.wikipedia.org/wiki/Floating_point#Problems_with_floating-point