Class: Float

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

Instance Method Summary collapse

Instance Method Details

#to_structObject

Split a float number into a Struct::Float fields: sign, biased exponent, fraction. It is the inverse of Struct::Float#to_f.

(2.0).to_struct          # => Struct::Float[1, 1024, 0]


41
42
43
44
# File 'lib/struct_float.rb', line 41

def to_struct
  x, = [self].pack("G").unpack("B*")
  Struct::Float[x[0] == ?1 ? -1 : 1, x[1,11].to_i(2), x[12,52].to_i(2)]
end

#ulpObject

Unit in the last place. The least significant bit of the fraction of a floating point number in its standard representation is its last place. The value represented by this bit (e.g., the absolute difference between two numbers whose structure are identical except for this bit) is the unit in the last place of that number.

(1.0).ulp                # => 2 ** -52
(1.1).ulp                # => 2 ** -52
(0.1).ulp                # => 2 ** -56


56
57
58
59
60
61
62
63
64
# File 'lib/struct_float.rb', line 56

def ulp
  2.0 ** if !finite?
    Infinity
  elsif zero?
    -1074
  else
    [Math.frexp(self).last - 53, -1074].max
  end
end