Issue #8883 has been updated by phluid61 (Matthew Kerwin).


=begin
I can't reproduce this in any version of Ruby that I have installed.  What is your Ruby 2.0 patch level?

 $ ruby2.0 -ve 'p Rational(2), Rational(3), Rational(2)/Rational(3)'
 ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]
 (2/1)
 (3/1)
 (2/3)
 $ ruby2.0 -ve 'p (Rational(2,7)+Rational(5,7))/((2+5)/7)'
 ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]
 (1/1)
 $ ruby2.1 -ve 'p (Rational(2,7)+Rational(5,7))/((2+5)/7)'
 ruby 2.1.0dev (2013-08-27 trunk 42696) [x86_64-linux]
 (1/1)
 $ ruby2.1 -ve 'p Rational(2), Rational(3), Rational(2)/Rational(3)'
 ruby 2.1.0dev (2013-08-27 trunk 42696) [x86_64-linux]
 (2/1)
 (3/1)
 (2/3)
=end

----------------------------------------
Bug #8883: Rational canonicalization unexpectedly converts to Fixnum
https://bugs.ruby-lang.org/issues/8883#change-41702

Author: melquiades (Paul Cantrell)
Status: Open
Priority: Normal
Assignee: 
Category: core
Target version: 
ruby -v: ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]
Backport: 1.9.3: UNKNOWN, 2.0.0: UNKNOWN


The documentation for Rational (http://www.ruby-doc.org/core-2.0.0/Rational.html) states that the result of creating or doing arithmetic on Rationals returns Rationals, as one would expect. Examples from the docs:

    Rational(1)      #=> (1/1)
    3.to_r           #=> (3/1)
    Rational(-2, 9) * Rational(-9, 2)  #=> (1/1)

These all work as documented in 1.9. In 2.0, however, they all return Fixnum:

    Rational(1)      #=> 1
    3.to_r           #=> 3
    Rational(-2, 9) * Rational(-9, 2)  #=> 1

This leads to unexpected behavior:

    Rational(2) / Rational(3)  # => 0  ...but returns (2/3) in 1.9

That behavior is potentially dangerous. Math that may *usually* work, but suddenly start suffering from truncation errors depending on intermediate results. For example:

  def should_always_return_one(a, b, c)
    (Rational(a, c) + Rational(b, c)) / (a + b) * c
  end

Under 1.9:

    should_always_return_one(2, 3, 7) #=> (1/1)
    should_always_return_one(2, 4, 7) #=> (1/1)
    should_always_return_one(2, 5, 7) #=> (1/1)
    should_always_return_one(2, 6, 7) #=> (1/1)

Under 2.0:

    should_always_return_one(2, 3, 7) #=> 1
    should_always_return_one(2, 4, 7) #=> 1
    should_always_return_one(2, 5, 7) #=> 0   Oops!
    should_always_return_one(2, 6, 7) #=> 1

Either the docs are wrong, or this is a bug. I vote bug. Whether arithmetic expressions truncate the result should not depend on whether intermediate values just happen to be integers! Such behavior renders Rational almost too dangerous to use in situations where exact results are required. (Yes, I realize that requiring 'mathn' fixes this, but even with such a workaround as an option, this is dangerously broken. See also #2121.) Note that floating point arithmetic does _not_ exhibit this behavior.



-- 
http://bugs.ruby-lang.org/