From: aoki_taichi via ruby-core Date: 2026-11-27T02:49:35+00:00 Subject: [ruby-core:127744] [Ruby Bug#22650] Difference in Rational to Float conversion Issue #22650 has been reported by aoki_taichi (������ ������). ---------------------------------------- Bug #22650: Difference in Rational to Float conversion https://bugs.ruby-lang.org/issues/22650 * Author: aoki_taichi (������ ������) * Status: Open * ruby -v: 4.0.10 * Backport: 3.3: UNKNOWN, 3.4: UNKNOWN, 4.0: UNKNOWN ---------------------------------------- I was surprised to see that for some Rational value r which is very close to 1, the result between Float(r) and r.to_f is different. The result between Math.sqrt(r) and r**0.5 was also different. ``` > ruby -v ruby 4.0.10 (2026-11-19 revision a704b7cd95) +PRISM [x86_64-linux] > cat almost_1_rat_to_float.rb def f(n) r = Rational(n, n + 1) f1 = Float(r) f2 = r.to_f puts "#{f1},#{f2},#{Math.sqrt(r)} #{r**0.5}" end f(+((2**1024) - (2**970) - 1)) f(+((2**1024) - (2**970) - 0)) f(-((2**1024) - (2**970) + 0)) f(-((2**1024) - (2**970) + 1)) > ruby almost_1_rat_to_float.rb 0.0,1.0,0.0 1.0 NaN,1.0,NaN 1.0 Infinity,1.0,Infinity 1.0 NaN,1.0,NaN 1.0 > ``` For the values I have tested, "to_f" and "**" seems to get a better result. Is this expected behavior? If I put -W2 option, the warnig is shown, so I am not sure if I should call this a bug. I was just wondering why it does not use the same algoritjm internally. ``` > ruby -W2 almost_1_rat_to_float.rb :196: warning: Integer out of Float range almost_1_rat_to_float.rb:5: warning: Integer out of Float range 0.0,1.0,0.0 1.0 :196: warning: Integer out of Float range :196: warning: Integer out of Float range almost_1_rat_to_float.rb:5: warning: Integer out of Float range almost_1_rat_to_float.rb:5: warning: Integer out of Float range NaN,1.0,NaN 1.0 :196: warning: Integer out of Float range almost_1_rat_to_float.rb:5: warning: Integer out of Float range Infinity,1.0,Infinity 1.0 :196: warning: Integer out of Float range :196: warning: Integer out of Float range almost_1_rat_to_float.rb:5: warning: Integer out of Float range almost_1_rat_to_float.rb:5: warning: Integer out of Float range NaN,1.0,NaN 1.0 ``` -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/