Math.sumPrecise()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
TheMath.sumPrecise()
static method takes an iterable of numbers and returns the sum of them. It is more precise than summing them up in a loop, because it avoids floating point precision loss in intermediate results.
Try it
console.log(Math.sumPrecise([1, 2]));// Expected output: 3console.log(Math.sumPrecise([1e20, 0.1, -1e20]));// Expected output: 0.1
Syntax
Math.sumPrecise(numbers)
Parameters
Return value
A number that is the sum of the numbers in thenumbers
iterable. If the iterable is empty, the return value is-0
(not0
).
Exceptions
TypeError
If
numbers
is not an iterable, or if any of the numbers in the iterable is not of the number type.
Description
BecausesumPrecise()
is a static method ofMath
, you always use it asMath.sumPrecise()
, rather than as a method of aMath
object you created (Math
is not a constructor).
The method is calledMath.sumPrecise()
because it is more precise than naïvely summing up numbers in a loop. Consider the following example:
let sum = 0;const numbers = [1e20, 0.1, -1e20];for (const number of numbers) { sum += number;}console.log(sum); // 0
The output is 0. This is because1e20 + 0.1
cannot be represented precisely in 64-bit floats, so the intermediate result is rounded to1e20
. Then, the sum of1e20
and-1e20
is0
, so the final result is0
.
Math.sumPrecise()
avoids this issue by using some specialized summing algorithm. It works as if the floating point numbers are summed up using their precise mathematical values, and the final result is then converted to the nearest representable 64-bit float. This still cannot avoid the0.1 + 0.2
precision problem:
console.log(Math.sumPrecise([0.1, 0.2])); // 0.30000000000000004
Because the floating point literals0.1
and0.2
already represent mathematical values greater than0.1
and0.2
, and their sum's closest 64-bit float representation is actually0.30000000000000004
.
Examples
Using Math.sumPrecise()
console.log(Math.sumPrecise([1, 2, 3])); // 6console.log(Math.sumPrecise([1e20, 0.1, -1e20])); // 0.1
Specifications
Specification |
---|
Math.sumPrecise # sec-math.sumprecise |