Kahan summation: Difference between revisions

Content added Content deleted
(Example implementation in R, with comparison to the standard sum() implementation)
m (added the a+b+c code)
Line 66: Line 66:
> # make R display more digits in the result
> # make R display more digits in the result
> options(digits=10)
> options(digits=10)
> a <- 10000.0
> b <- 3.14159
> c <- 2.71828
> a + b + c
[1] 10005.85987
> # no problem there
> input <- c(10000.0, 3.14159, 2.71828)
> input <- c(10000.0, 3.14159, 2.71828)
> kahansum(input)
> kahansum(input)
[1] 10005.85987
[1] 10005.85987
> # compare with the standard sum() function
> # for completeness, let's compare with the standard sum() function
> sum(input)
> sum(input)
[1] 10005.85987
[1] 10005.85987
> # seems like R does the "right thing"
> # seems like R does the "right thing"
> # bonus:
> # let's use the Dr. Dobbs example (http://www.drdobbs.com/floating-point-summation/184403224)
> # let's use the Dr. Dobbs example (http://www.drdobbs.com/floating-point-summation/184403224)
> input <- c(1.0, 1.0e10, -1.0e10)
> input <- c(1.0, 1.0e10, -1.0e10)