Module: Flt::Support::AuxiliarFunctions

Included in:
Num
Defined in:
lib/flt/support.rb

Constant Summary collapse

NBITS_BLOCK =
32
NBITS_LIMIT =
Math.ldexp(1,Float::MANT_DIG).to_i
MAXIMUM_SMALLISH_INTEGER =
(2 << 63) - 1
NDIGITS_BLOCK =
50
NDIGITS_LIMIT =
Float::MAX.to_i

Class Method Summary collapse

Class Method Details

._nbits(x) ⇒ Object

Number of bits in binary representation of the positive integer n, or 0 if n == 0.

Raises:

  • (TypeError)


75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/flt/support.rb', line 75

def _nbits(x)
  raise  TypeError, "The argument to _nbits should be nonnegative." if x < 0
  # Ruby 2.1 introduced Integer#bit_length
  return x.bit_length if x.respond_to? :bit_length
  if x <= MAXIMUM_SMALLISH_INTEGER
    return 0 if x==0
    x.to_s(2).length
  elsif x <= NBITS_LIMIT
    Math.frexp(x).last
  else
    n = 0
    while x!=0
      y = x
      x >>= NBITS_BLOCK
      n += NBITS_BLOCK
    end
    n += y.to_s(2).length - NBITS_BLOCK if y!=0
    n
  end
end

._ndigits(x, b) ⇒ Object

Number of base b digits in an integer

Raises:

  • (TypeError)


100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/flt/support.rb', line 100

def _ndigits(x, b)
  raise  TypeError, "The argument to _ndigits should be nonnegative." if x < 0
  return 0 unless x.is_a?(Integer)
  return _nbits(x) if b==2
  if x <= MAXIMUM_SMALLISH_INTEGER
    return 0 if x==0
    x.to_s(b).length
  elsif x <= NDIGITS_LIMIT
    (Math.log(x)/Math.log(b)).floor + 1
  else
    n = 0
    block = b**NDIGITS_BLOCK
    while x!=0
      y = x
      x /= block
      n += NDIGITS_BLOCK
    end
    n += y.to_s(b).length - NDIGITS_BLOCK if y!=0
    n
  end
end

.detect_float_roundingObject



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/flt/support.rb', line 124

def detect_float_rounding
  x = x = Math::ldexp(1, Float::MANT_DIG+1) # 10000...00*Float::RADIX**2 == Float::RADIX**(Float::MANT_DIG+1)
  y = x + Math::ldexp(1, 2)                 # 00000...01*Float::RADIX**2 == Float::RADIX**2
  h = Float::RADIX/2
  b = h*Float::RADIX
  z = Float::RADIX**2 - 1
  if x + 1 == y
    if (y + 1 == y) && Float::RADIX==10
      :up05
    elsif -x - 1 == -y
      :up
    else
      :ceiling
    end
  else # x + 1 == x
    if x + z == x
      if -x - z == -x
        :down
      else
        :floor
      end
    else # x + z == y
      # round to nearest
      if x + b == x
        if y + b == y
          :half_down
        else
          :half_even
        end
      else # x + b == y
        :half_up
      end
    end
  end
end