Find the sum of a vector

naivesum(x)

kahansum(x)

pwisesum(x)

Arguments

x

a vector of numbers to be summed

Value

the sum

Details

naivesum calculates the sum of a vector by keeping a counter and repeatedly adding the next value to the interim sum. kahansum uses Kahan's algorithm to capture the low-order precision loss and ensure that the loss is reintegrated into the final sum. pwisesum is a recursive implementation of the piecewise summation algorithm that divides the vector in two and adds the individual vector sums for a result.

Examples

k <- 1:10^6
n <- sample(k, 1)
bound <- sample(k, 2)
bound.upper <- max(bound) - 10^6 / 2
bound.lower <- min(bound) - 10^6 / 2
x <- runif(n, bound.lower, bound.upper)
naivesum(x)
#> [1] 102354494310
kahansum(x)
#> [1] 102354494310
pwisesum(x)
#> [1] 102354494310