Module: Bang::NumericMixin

Included in:
Numeric
Defined in:
lib/bang.rb

Overview

Mixin for Numeric class that adds ‘#within?` and `#close?`.

Instance Method Summary collapse

Instance Method Details

#close?(other, epsilon) ⇒ true, false

Is this value within a given relative ‘epsilon` of another?

Returns:

  • (true, false)

    True if within relative epsilon, otherwise false.



238
239
240
241
242
243
244
# File 'lib/bang.rb', line 238

def close?(other, epsilon)
  a, b, e = self.to_f, other.to_f, epsilon.to_f

  d = b * e

  (b - d) <= a && (b + d) >= a
end

#within?(other, delta) ⇒ true, false

Is this value within a given absolute ‘delta` of another?

Returns:

  • (true, false)

    True if within absolute delta, otherwise false.



227
228
229
230
231
# File 'lib/bang.rb', line 227

def within?(other, delta)
  a, b, d = self.to_f, other.to_f, delta.to_f

  (b - d) <= a && (b + d) >= a   
end