Created
December 17, 2008 22:15
-
-
Save dball/37260 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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