Skip to content

Instantly share code, notes, and snippets.

@enthal
Created June 2, 2012 02:10
Show Gist options
  • Save enthal/2856161 to your computer and use it in GitHub Desktop.
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
# 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
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