Skip to content
Browse files

Changes to float comparison again

 * Use difference if either value is zero (because there's no scale)
 * Use ratio otherwise (because scale is important)
 * Tests for tiny and huge numbers
  • Loading branch information...
1 parent 5b8184e commit c4ebedf290775bc425c73721586b6c9f3a53bd77 @gsinclair committed Dec 22, 2010
Showing with 16 additions and 3 deletions.
  1. +8 −3 lib/attest/assertion_classes.rb
  2. +8 −0 test/attest_test.rb
View
11 lib/attest/assertion_classes.rb
@@ -272,9 +272,14 @@ def initialize(mode, *args, &block)
@epsilon ||= EPSILON
end
def run
- difference = (@expected - @actual).abs
- # we want the difference to be a small percentage of the expected value
- difference < 1e-10 or (difference / @expected).abs <= @epsilon
+ if @actual.zero? or @expected.zero?
+ # There's no scale, so we can only go on difference.
+ (@actual - @expected) < @epsilon
+ else
+ # We go by ratio. The ratio of two equal numbers is one, so the ratio
+ # of two practically-equal floats will be very nearly one.
+ (@actual/@expected - 1).abs < @epsilon
+ end
end
def message
String.new.tap { |str|
View
8 test/attest_test.rb
@@ -159,6 +159,14 @@
Ft a, b, 0.000000001
Ft b, a, 0.000000001
end
+ D 'tiny numbers' do
+ Ft 1.234567e-50, 1.234568e-50
+ Ft! 1.234567e-50, 1.234567e-51
+ end
+ D 'huge numbers' do
+ Ft 1.234567e50, 1.234568e50
+ Ft! 1.234567e50, 1.234567e51
+ end
end
D 'Id' do

0 comments on commit c4ebedf

Please sign in to comment.
Something went wrong with that request. Please try again.