From: "Peña, Botp" Date: 2007-08-30T11:14:44+09:00 Subject: Re: Bug in % (Float)? From: Charlie Lehardy [mailto:charlie.lehardy@gmail.com] : # irb(main):001:0> 1 % 0.1 # => 0.1 # # Shouldn't 1 % 0.1 be 0.0 and not 0.1? never trust floats in division :) ruby tries to be friendly at the expense of more surprises... irb(main):343:0> system "qri numeric.divmod | head -7" --------------------------------------------------------- Numeric#divmod num.divmod( aNumeric ) -> anArray ------------------------------------------------------------------------ Returns an array containing the quotient and modulus obtained by dividing num by aNumeric. If q, r = x.divmod(y), then q = floor(float(x)/float(y)) => true irb(main):345:0> 1.divmod 0.1 => [9, 0.1] irb(main):347:0> 9*0.1+0.1 => 1.0 :( you can use Rational instead (or BigDecimal, see below), irb(main):358:0> x=Rational(1,1) => Rational(1, 1) irb(main):360:0> y=Rational(1,10) => Rational(1, 10) irb(main):361:0> r = x % y => Rational(0, 1) irb(main):362:0> puts r 0 => nil # Also, look at the # following example: # irb(main):009:0> a += (a % b) if ((a % b) > 0) # => 1.59999999999999 again, do not put all your trust in floats or in machines for that matter :) irb(main):344:0> 1.5.divmod 0.1 => [14, 0.0999999999999999] this time, let us use BigDecimal. irb(main):369:0> require 'bigdecimal' => true irb(main):375:0* x=BigDecimal.new "1.5" => # irb(main):376:0> y=BigDecimal.new "0.1" => # irb(main):377:0> r = x%y => # irb(main):378:0> puts r 0.0 => nil irb(main):379:0> q,r = x.divmod(y) => [#, #] irb(main):380:0> puts q, r 0.15E2 0.0 => nil BigDecimal is powerful, Rational is less heavy. Your choice though. kind regards -botp