Stage 2.7 Draft / October 27, 2024

Math.sumPrecise

Contributing to this Proposal

You can discuss this proposal on GitHub.

1 Introduction

This proposal adds a method for summing multiple numbers.

2 Math.sumPrecise ( items )

Given an iterable of Numbers, this function sums each value in the iterable and returns their sum. If any value is not a Number it throws a TypeError exception.

It performs the following steps when called:

  1. Perform ? RequireObjectCoercible(items).
  2. Let iteratorRecord be ? GetIterator(items, sync).
  3. Let state be minus-zero.
  4. Let sum be 0.
  5. Let count be 0.
  6. Let next be not-started.
  7. Repeat, while next is not done,
    1. Set next to ? IteratorStepValue(iteratorRecord).
    2. If next is not done, then
      1. Set count to count + 1.
      2. If count ≥ 253, then
        1. Let error be ThrowCompletion(a newly created RangeError object).
        2. Return ? IteratorClose(iteratorRecord, error).
      3. NOTE: The above case is not expected to be reached in practice and is included only so that implementations may rely on inputs being "reasonably sized" without violating this specification.
      4. If next is not a Number, then
        1. Let error be ThrowCompletion(a newly created TypeError object).
        2. Return ? IteratorClose(iteratorRecord, error).
      5. Let n be next.
      6. If state is not not-a-number, then
        1. If n is NaN, then
          1. Set state to not-a-number.
        2. Else if n is +∞𝔽, then
          1. If state is minus-infinity, set state to not-a-number.
          2. Else, set state to plus-infinity.
        3. Else if n is -∞𝔽, then
          1. If state is plus-infinity, set state to not-a-number.
          2. Else, set state to minus-infinity.
        4. Else if n is not -0𝔽 and state is either minus-zero or finite, then
          1. Set state to finite.
          2. Set sum to sum + (n).
  8. If state is not-a-number, return NaN.
  9. If state is plus-infinity, return +∞𝔽.
  10. If state is minus-infinity, return -∞𝔽.
  11. If state is minus-zero, return -0𝔽.
  12. Return 𝔽(sum).
  13. NOTE: The value of sum can be computed without arbitrary-precision arithmetic by a variety of algorithms. One such is the "Grow-Expansion" algorithm given in Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates by Jonathan Richard Shewchuk. A more recent algorithm is given in "Fast exact summation using small and large superaccumulators", code for which is available at https://gitlab.com/radfordneal/xsum.