Skip to content

Instantly share code, notes, and snippets.

@dball
Created December 17, 2008 22:15
Show Gist options
  • Save dball/37260 to your computer and use it in GitHub Desktop.
Save dball/37260 to your computer and use it in GitHub Desktop.
require 'rational'
module Almost
EPSILON = 0.001
module InstanceMethods
def almost(epsilon = EPSILON)
Almost::Number.new(self, epsilon)
end
end
class Number
def initialize(value, epsilon)
@value = value
@epsilon = epsilon
end
def ==(other)
max = (@value.abs > other.abs ? @value : other)
(fr, exp) = Math.frexp(max)
delta = Math.ldexp(@epsilon, exp)
difference = @value - other
!(difference > delta || difference < -delta)
end
end
end
class Integer
include Almost::InstanceMethods
end
class Float
include Almost::InstanceMethods
end
class BigDecimal
include Almost::InstanceMethods
end
class Rational
include Almost::InstanceMethods
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment