Project

General

Profile

Actions

Bug #14926

closed

Different results between Enumerable#sum and #reduce when Float::INFINITY present

Added by swistak35 (Rafał Łasocha) over 5 years ago. Updated over 5 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]
[ruby-core:88024]

Description

When Float::INFINITY is present in array, Enumerable#sum and Enumerable#reduce(0, &:+) are giving different results.

puts [Float::INFINITY].sum
puts [Float::INFINITY].reduce(0, &:+)

results in

NaN
Infinity

And I would expect both of them to be Infinity (meaning: #sum is working incorrectly).

Checked on ruby 2.5.1p57 and ruby 2.4.3p205, both have the same bug.

Updated by shevegen (Robert A. Heiler) over 5 years ago

I sort of agree; I would have expected the same result.

Other arrays with numbers output the same result:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce(0, &:+) # => 55
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sum            # => 55

So the result of .sum on infinity seems awkward if .reduce(0, &:+) leads
to Infinity.

I am a bit surprised about infinity though:

a = [Float::INFINITY].reduce(0, &:+)
b = [Float::INFINITY]

puts a
puts b

puts (a == b) # => false

I also would have expected the latter to be true. Infinity confuses
me a lot so I will leave others to this issue. :)

Updated by marcandre (Marc-Andre Lafortune) over 5 years ago

Yes, definitely a bug in the algorithm trying to minimize floating errors. Result must be Float::INFINITY.

shevegen (Robert A. Heiler) wrote:

I am a bit surprised about infinity though:

a = [Float::INFINITY].reduce(0, &:+)
b = [Float::INFINITY]

puts (a == b) # => false

Using p instead of puts will show you you are comparing an array with float...

p a  # => Infinity
p b  # => [Infinity]
Actions #3

Updated by nobu (Nobuyoshi Nakada) over 5 years ago

  • Backport changed from 2.3: UNKNOWN, 2.4: UNKNOWN, 2.5: UNKNOWN to 2.3: DONTNEED, 2.4: REQUIRED, 2.5: REQUIRED
Actions #4

Updated by nobu (Nobuyoshi Nakada) over 5 years ago

  • Status changed from Open to Closed

Applied in changeset trunk|r64014.


fix sum on infinity

Updated by usa (Usaku NAKAMURA) over 5 years ago

  • Backport changed from 2.3: DONTNEED, 2.4: REQUIRED, 2.5: REQUIRED to 2.3: DONTNEED, 2.4: DONE, 2.5: REQUIRED

ruby_2_4 r64562 merged revision(s) 64014.

Updated by nagachika (Tomoyuki Chikanaga) over 5 years ago

  • Backport changed from 2.3: DONTNEED, 2.4: DONE, 2.5: REQUIRED to 2.3: DONTNEED, 2.4: DONE, 2.5: DONE

ruby_2_5 r64603 merged revision(s) 64014.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0