Class: Float

Inherits:
Object
  • Object
show all
Defined in:
lib/astro-algo.rb

Instance Method Summary collapse

Instance Method Details

#to_rObject

Convert Float to Rational. Algorithm from Dave Burt: blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/142199



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/astro-algo.rb', line 30

def to_r
    return Rational(0, 1) if self == 0.0
    x = self
    negative = false
    if x < 0.0
        x = -x
        negative = true
    end
    f, e = Math.frexp(x)
    # raise unless 0.5 <= f and f < 1.0
    # x = f * 2**e exactly

    # Suck up _chunk_ bits at a time; 28 is enough so that we suck
    # up all bits in 2 iterations for all known binary double-
    # precision formats, and small enough to fit in an int.
    chunk = 28
    top = 0
    # invariant: x = (top + f) * 2**e exactly
    while f > 0.0
        f = Math.ldexp(f, chunk)
        digit = f.to_i
        raise unless digit >> chunk == 0
        top = (top << chunk) | digit
        f -= digit
        # raise unless 0.0 <= f and f < 1.0
        e -= chunk
    end
    # raise if top == 0

    # now x = top * 2**e exactly; fold in 2**e
    r = Rational(top, 1)
    if e > 0
        r *= 2**e
    else
        r /= 2**-e
    end
    negative ? -r : r
end