Skip to content

Commit 4c1e531

Browse files
nobuetiennebarrie
authored andcommitted
[Bug #22092] Improve Array#sum when the initial value is a Float
1 parent 6c080d7 commit 4c1e531

2 files changed

Lines changed: 8 additions & 2 deletions

File tree

array.c

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8247,7 +8247,11 @@ rb_ary_sum(int argc, VALUE *argv, VALUE ary)
82478247
n = 0;
82488248
r = Qundef;
82498249

8250-
if (!FIXNUM_P(v) && !RB_BIGNUM_TYPE_P(v) && !RB_TYPE_P(v, T_RATIONAL)) {
8250+
bool init_is_float = RB_FLOAT_TYPE_P(v);
8251+
if (init_is_float) {
8252+
v = LONG2FIX(0);
8253+
}
8254+
else if (!RB_INTEGER_TYPE_P(v) && !RB_TYPE_P(v, T_RATIONAL)) {
82518255
i = 0;
82528256
goto init_is_a_value;
82538257
}
@@ -8275,12 +8279,13 @@ rb_ary_sum(int argc, VALUE *argv, VALUE ary)
82758279
goto not_exact;
82768280
}
82778281
v = finish_exact_sum(n, r, v, argc!=0);
8282+
if (init_is_float) v = rb_float_plus(argv[0], v);
82788283
return v;
82798284

82808285
not_exact:
82818286
v = finish_exact_sum(n, r, v, i!=0);
82828287

8283-
if (RB_FLOAT_TYPE_P(e)) {
8288+
if (init_is_float ? (--i, e = argv[0], true) : RB_FLOAT_TYPE_P(e)) {
82848289
/*
82858290
* Kahan-Babuska balancing compensated summation algorithm
82868291
* See https://link.springer.com/article/10.1007/s00607-005-0139-x

test/ruby/test_array.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3524,6 +3524,7 @@ def test_sum
35243524
assert_float_equal(3.5, [3].sum(0.5))
35253525
assert_float_equal(8.5, [3.5, 5].sum)
35263526
assert_float_equal(10.5, [2, 8.5].sum)
3527+
assert_float_equal(1_000 * 0.1, Array.new(1_000, 0.1).sum(0.0))
35273528
assert_float_equal((FIXNUM_MAX+1).to_f, [FIXNUM_MAX, 1, 0.0].sum)
35283529
assert_float_equal((FIXNUM_MAX+1).to_f, [0.0, FIXNUM_MAX+1].sum)
35293530

0 commit comments

Comments
 (0)