3

Can someone clarify why ruby returns such big numbers when using to_r

for example:

a = 0.025
a.to_r
3602879701896397/144115188075855872.

Why not use 1/40?

hbt
  • 1,011
  • 3
  • 16
  • 28

1 Answers1

4

This sounds like a typical floating point problem, but hidden inside. While 0.025 may be represented exactly, the function to_r will no doubt perform various floating-point operations internally which are necessarily inexact. The result 3602879701896397/144115188075855872 will no doubt match the intermediate, transformed version of a more closely than your proposal 1/40.

Now 3602879701896397/144115188075855872 is extremely close to being the same as 1/40. But it is not quite equal, so is not simplified.

For more information, look at some of the previous questions related to inexact floating point. This is a nuanced case and a good question therefore, but has its fundamentals in the same things. I'm looking into the ruby C implementation of Float#to_r for more details.

Community
  • 1
  • 1
Peter
  • 127,331
  • 53
  • 180
  • 211
  • 2
    Hmm... `"0.025".to_r #=> (1/40)`. – steenslag Dec 25 '12 at 23:33
  • To further @steenslag: (in Ruby 2.1.5) `(2/5.0).to_r #=> (3602879701896397/9007199254740992)` yet `(2/5.0).to_s.to_r #=> (2/5)`. Seems the string implementation of to_r is more accurate than the float implementation? – Chris Hall Aug 03 '15 at 16:10