Project

General

Profile

Actions

Bug #22650

open

Difference in Rational to Float conversion

Bug #22650: Difference in Rational to Float conversion

Added by aoki_taichi (太一 青木) 2 days ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:127744]

Description

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
<internal:kernel>: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
<internal:kernel>:196: warning: Integer out of Float range
<internal:kernel>: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
<internal:kernel>: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
<internal:kernel>:196: warning: Integer out of Float range
<internal:kernel>: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

No data to display

Actions

Also available in: PDF Atom