Sort your data to get a accurate sum
Based on a message of Jan Motl in r-help discussion list.
If the numbers are positive, to get an accurate sum, sort the data by increasing order.
> x <- c(rep(1.1, 10000), 10^16)
> dput(c(sum(sort(x, decreasing = TRUE)), sum(sort(x, decreasing = FALSE))))
c(10000000000010996, 10000000000011000)
If the numbers are negative, to get an accurate sum, sort the data by decreasing order.
> x <- c(rep(-1.1, 10000), -10^16)
> dput(c(sum(sort(x, decreasing = TRUE)), sum(sort(x, decreasing = FALSE))))
c(-10000000000011000, -10000000000010996)
If the numbers are both positive and negative, no change.
> x <- c(rep(1.1, 5000), rep(-1.1, 5000), 10^16)
> dput(c(sum(sort(x, decreasing = TRUE)), sum(sort(x, decreasing = FALSE))))
c(1e+16, 1e+16)
If the numbers are positive, to get an accurate sum, sort the data by increasing order.
> x <- c(rep(1.1, 10000), 10^16)
> dput(c(sum(sort(x, decreasing = TRUE)), sum(sort(x, decreasing = FALSE))))
c(10000000000010996, 10000000000011000)
If the numbers are negative, to get an accurate sum, sort the data by decreasing order.
> x <- c(rep(-1.1, 10000), -10^16)
> dput(c(sum(sort(x, decreasing = TRUE)), sum(sort(x, decreasing = FALSE))))
c(-10000000000011000, -10000000000010996)
If the numbers are both positive and negative, no change.
> x <- c(rep(1.1, 5000), rep(-1.1, 5000), 10^16)
> dput(c(sum(sort(x, decreasing = TRUE)), sum(sort(x, decreasing = FALSE))))
c(1e+16, 1e+16)
Higham NJ (2002) Accuracy and stability of numerical algorithms. Society for Industrial and Applied Mathematics, Philadelphia, USA
Chapter 4 - Summation
Commentaires
Enregistrer un commentaire