Kahan summation: Difference between revisions
Content added Content deleted
(→{{header|Python}}: Contrast Pythons sum()) |
(Example implementation in R, with comparison to the standard sum() implementation) |
||
Line 48: | Line 48: | ||
Decimal('10005.85987') |
Decimal('10005.85987') |
||
>>> </lang> |
>>> </lang> |
||
=={{header|R}}== |
|||
<lang> |
|||
> # A straightforward implementation of the algorithm |
|||
> kahansum <- function(x) { |
|||
+ ks <- 0 |
|||
+ c <- 0 |
|||
+ for(i in 1:length(x)) { |
|||
+ y <- x[i] - c |
|||
+ kt <- ks + y |
|||
+ c = (kt - ks) - y |
|||
+ ks = kt |
|||
+ } |
|||
+ ks |
|||
+ } |
|||
> # make R display more digits in the result |
|||
> options(digits=10) |
|||
> input <- c(10000.0, 3.14159, 2.71828) |
|||
> kahansum(input) |
|||
[1] 10005.85987 |
|||
> # compare with the standard sum() function |
|||
> sum(input) |
|||
[1] 10005.85987 |
|||
> # seems like R does the "right thing" |
|||
> # let's use the Dr. Dobbs example (http://www.drdobbs.com/floating-point-summation/184403224) |
|||
> input <- c(1.0, 1.0e10, -1.0e10) |
|||
> kahansum(input) |
|||
[1] 1 |
|||
> sum(input) |
|||
[1] 1 |
|||
> # again, R does it right |
|||
</lang> |