Created
June 2, 2012 02:10
-
-
Save enthal/2856161 to your computer and use it in GitHub Desktop.
SafeFloat: a half baked ruby way to change how math works in some interesting ways... probably a bad idea but at least the specs pass
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
# Provides JSON-safe division, === with a fudge factor, allowance of integer division | |
class SafeFloat | |
FUDGE = 0.0000001 | |
def initialize v | |
@v = v | |
end | |
def / other | |
# p "#{@v} / #{other.to_f} == #{@v / other.to_f}" | |
self.class.new(@v / other.to_f) if other != 0 # nil instead of NaN | |
end | |
def + other | |
other = other.to_f if self.class===other | |
@v + other # allow faster integer addition if @v is an integer and not a float | |
end | |
def === other | |
@v.between?(other.to_f-FUDGE, other.to_f+FUDGE) | |
end | |
def to_f | |
@v.to_f | |
end | |
def method_missing name, *args, &block | |
# p name | |
args.map! {|arg| self.class===arg ? arg.to_f : arg} | |
self.class.new(@v.send(name, *args, &block)) | |
end | |
end |
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
describe Processors::MemberSponsor::Aggregates::SafeFloat do | |
subject {Processors::MemberSponsor::Aggregates::SafeFloat} | |
it {(subject.new(1)/2).should === 0.5} | |
it {(subject.new(1)/2).should === 0.5} | |
it {(subject.new(1)/2).should === subject.new(0.5)} | |
it {(subject.new(1)/subject.new(2)).should === 0.5} | |
it {(subject.new(1)/subject.new(2)).should === subject.new(0.5)} | |
it {(subject.new(1)).should_not == 1.000000000001} | |
it {(subject.new(1)).should === 1.000000000001} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment