summaryrefslogtreecommitdiff
path: root/enum.c
diff options
context:
space:
mode:
authormrkn <mrkn@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2016-12-06 13:40:31 (GMT)
committermrkn <mrkn@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2016-12-06 13:40:31 (GMT)
commit48f5f5915b0c357b05a9dda2732470bf67ebd691 (patch)
tree770f8065f1ef2a61f38cc5941334b759f43172f9 /enum.c
parent0cb1a2b81232b5a64242fc6899d72be22b35495f (diff)
array.c, enum.c: change sum algorithm
* array.c (rb_ary_sum): change the algorithm to Kahan-Babuska balancing summation to be more precise. [Feature #12871] [ruby-core:77771] * enum.c (sum_iter, enum_sum): ditto. * test_array.rb, test_enum.rb: add an assertion for the above change. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@57001 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'enum.c')
-rw-r--r--enum.c17
1 files changed, 11 insertions, 6 deletions
diff --git a/enum.c b/enum.c
index b328003..5a56dca 100644
--- a/enum.c
+++ b/enum.c
@@ -3644,8 +3644,11 @@ sum_iter(VALUE i, struct enum_sum_memo *memo)
}
}
else if (RB_FLOAT_TYPE_P(v)) {
- /* Kahan's compensated summation algorithm */
- double x, y, t;
+ /*
+ * Kahan-Babuska balancing compensated summation algorithm
+ * See http://link.springer.com/article/10.1007/s00607-005-0139-x
+ */
+ double x, t;
float_value:
if (RB_FLOAT_TYPE_P(i))
@@ -3662,9 +3665,11 @@ sum_iter(VALUE i, struct enum_sum_memo *memo)
goto some_value;
}
- y = x - c;
- t = f + y;
- c = (t - f) - y;
+ t = f + x;
+ if (fabs(f) >= fabs(x))
+ c += ((f - t) + x);
+ else
+ c += ((x - t) + f);
f = t;
}
else {
@@ -3788,7 +3793,7 @@ enum_sum(int argc, VALUE* argv, VALUE obj)
rb_block_call(obj, id_each, 0, 0, enum_sum_i, (VALUE)&memo);
if (memo.float_value) {
- return DBL2NUM(memo.f);
+ return DBL2NUM(memo.f + memo.c);
}
else {
if (memo.n != 0)