diff options
Diffstat (limited to 'spec/ruby/core/array')
-rw-r--r-- | spec/ruby/core/array/sum_spec.rb | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/spec/ruby/core/array/sum_spec.rb b/spec/ruby/core/array/sum_spec.rb index 39c769d328..8ca8353a67 100644 --- a/spec/ruby/core/array/sum_spec.rb +++ b/spec/ruby/core/array/sum_spec.rb @@ -9,6 +9,35 @@ describe "Array#sum" do [1, 2, 3].sum { |i| i * 10 }.should == 60 end + # https://bugs.ruby-lang.org/issues/12217 + # https://github.com/ruby/ruby/blob/master/doc/ChangeLog-2.4.0#L6208-L6214 + it "uses Kahan's compensated summation algorithm for precise sum of float numbers" do + floats = [2.7800000000000002, 5.0, 2.5, 4.44, 3.89, 3.89, 4.44, 7.78, 5.0, 2.7800000000000002, 5.0, 2.5] + naive_sum = floats.reduce { |sum, e| sum + e } + naive_sum.should == 50.00000000000001 + floats.sum.should == 50.0 + end + + it "handles infinite values and NaN" do + [1.0, Float::INFINITY].sum.should == Float::INFINITY + [1.0, -Float::INFINITY].sum.should == -Float::INFINITY + [1.0, Float::NAN].sum.should.nan? + + [Float::INFINITY, 1.0].sum.should == Float::INFINITY + [-Float::INFINITY, 1.0].sum.should == -Float::INFINITY + [Float::NAN, 1.0].sum.should.nan? + + [Float::NAN, Float::INFINITY].sum.should.nan? + [Float::INFINITY, Float::NAN].sum.should.nan? + + [Float::INFINITY, -Float::INFINITY].sum.should.nan? + [-Float::INFINITY, Float::INFINITY].sum.should.nan? + + [Float::INFINITY, Float::INFINITY].sum.should == Float::INFINITY + [-Float::INFINITY, -Float::INFINITY].sum.should == -Float::INFINITY + [Float::NAN, Float::NAN].sum.should.nan? + end + it "returns init value if array is empty" do [].sum(-1).should == -1 end |