Class: Float

Inherits:
Object
  • Object
show all
Defined in:
lib/WSK/Functions.rb

Overview

Convert a float to a Rational

Instance Method Summary collapse

Instance Method Details

#to_rObject

Convert to a Rational

Return
  • Rational: Corresponding Rational



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/WSK/Functions.rb', line 24

def to_r
  rResult = nil

  if (self.nan?)
    rResult = Rational(0,0) # Div by zero error
  elsif (self.infinite?)
    rResult = Rational(self<0 ? -1 : 1,0) # Div by zero error
  else
    lSign, lExponent, lFloat = [self].pack("G").unpack("B*").first.unpack("AA11A52")
    lSign = (-1)**lSign.to_i
    lExponent = lExponent.to_i(2)
    if ((lExponent.nonzero?) and
        (lExponent<2047))
      rResult = Rational(lSign)*Rational(2)**(lExponent-1023)*Rational("1#{lFloat}".to_i(2),0x10000000000000)
    elsif (lExponent.zero?)
      rResult = Rational(lSign)*Rational(2)**(-1024)*Rational("0#{lFloat}".to_i(2),0x10000000000000)
    end
  end

  return rResult
end