This method avoids loss of precision by tracking multiple intermediate partial sums. Based on python's math.fsum

fsum(numbers)

Arguments

numbers

A vector of numbers to sum.

Value

Sum of numbers without loss of precision

The algorithm's accuracy depends on IEEE-754 arithmetic guarantees and the typical case where the rounding mode is half-even. On some non-Windows builds, the underlying C library uses extended precision addition and may occasionally double-round an intermediate sum causing it to be off in its least significant bit.

Author

Matthew Fidler (R implementation), Raymond Hettinger, Jonathan Shewchuk, Python Team

Examples

sum(c(1,1e100,1,-1e100)) ## Should be 2, gives 0
#> [1] 0
fsum(c(1,1e100,1,-1e100)) ## Gives 2.
#> [1] 2