Class: Arrow::HalfFloat

Inherits:
Object
  • Object
show all
Defined in:
lib/arrow/half-float.rb

Constant Summary collapse

MAX =
65504
MIN =
-65504
EXPONENT_N_BITS =
5
EXPONENT_MASK =
(2 ** EXPONENT_N_BITS) - 1
EXPONENT_BIAS =
15
FRACTION_N_BITS =
10
FRACTION_MASK =
(2 ** FRACTION_N_BITS) - 1
FRACTION_DENOMINATOR =
2.0 ** FRACTION_N_BITS

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ HalfFloat

Returns a new instance of HalfFloat.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/arrow/half-float.rb', line 32

def initialize(*args)
  n_args = args.size
  case n_args
  when 1
    if args[0].is_a?(Float)
      @sign, @exponent, @fraction = deconstruct_float(args[0])
    else
      @sign, @exponent, @fraction = deconstruct_uint16(args[0])
    end
  when 3
    @sign, @exponent, @fraction = *args
  else
    message = "wrong number of arguments (given #{n_args}, expected 1 or 3)"
    raise ArgumentError, message
  end
end

Instance Attribute Details

#exponentObject (readonly)

Returns the value of attribute exponent.



30
31
32
# File 'lib/arrow/half-float.rb', line 30

def exponent
  @exponent
end

#fractionObject (readonly)

Returns the value of attribute fraction.



31
32
33
# File 'lib/arrow/half-float.rb', line 31

def fraction
  @fraction
end

#signObject (readonly)

Returns the value of attribute sign.



29
30
31
# File 'lib/arrow/half-float.rb', line 29

def sign
  @sign
end

Instance Method Details

#packObject



74
75
76
# File 'lib/arrow/half-float.rb', line 74

def pack
  [to_uint16].pack("S")
end

#to_fObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/arrow/half-float.rb', line 49

def to_f
  if @exponent == EXPONENT_MASK
    if @sign.zero?
      Float::INFINITY
    else
      -Float::INFINITY
    end
  else
    if @exponent.zero?
      implicit_fraction = 0
    else
      implicit_fraction = 1
    end
    ((-1) ** @sign) *
      (2 ** (@exponent - EXPONENT_BIAS)) *
      (implicit_fraction + @fraction / FRACTION_DENOMINATOR)
  end
end

#to_uint16Object



68
69
70
71
72
# File 'lib/arrow/half-float.rb', line 68

def to_uint16
  (@sign << (EXPONENT_N_BITS + FRACTION_N_BITS)) ^
    (@exponent << FRACTION_N_BITS) ^
    @fraction
end