Stage 2.7 Draft / October 27, 2024
Math.sumPrecise
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:
- Perform ? RequireObjectCoercible(items).
- Let iteratorRecord be ? GetIterator(items, sync).
- Let state be minus-zero.
- Let sum be 0.
- Let count be 0.
- Let next be not-started.
- Repeat, while next is not done,
- Set next to ? IteratorStepValue(iteratorRecord).
- If next is not done, then
- Set count to count + 1.
- If count ≥ 253, then
- Let error be ThrowCompletion(a newly created RangeError object).
- Return ? IteratorClose(iteratorRecord, error).
- 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.
- If next is not a Number, then
- Let error be ThrowCompletion(a newly created TypeError object).
- Return ? IteratorClose(iteratorRecord, error).
- Let n be next.
- If state is not not-a-number, then
- If n is NaN, then
- Set state to not-a-number.
- Else if n is +∞𝔽, then
- If state is minus-infinity, set state to not-a-number.
- Else, set state to plus-infinity.
- Else if n is -∞𝔽, then
- If state is plus-infinity, set state to not-a-number.
- Else, set state to minus-infinity.
- Else if n is not -0𝔽 and state is either minus-zero or finite, then
- Set state to finite.
- Set sum to sum + ℝ(n).
- If state is not-a-number, return NaN.
- If state is plus-infinity, return +∞𝔽.
- If state is minus-infinity, return -∞𝔽.
- If state is minus-zero, return -0𝔽.
- Return 𝔽(sum).
- 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.