On Tue, Aug 23, 2011 at 6:56 PM, Daniel Lai <dan...@bccrc.ca> wrote: > Hi Barry, > > Shock and horror indeed, addition is not _associative_, at least for > floating point arithmetic [1]. > > Flipping the order of the operands seems to be the explanation of the > discrepancies between R and MATLAB as you suggest: > > In R: > a = 0.812672 > b = 0.916541 > c = 0.797810 > sprintf('%.30f', a+b+c) > [1] "2.527023000000000241271891354700" > sprintf('%.30f', c+a+b) > [1] "2.527022999999999797182681504637" > sprintf('%.30f', sum(c(a,b,c))) > [1] "2.527022999999999797182681504637" > > In MATLAB: > a = 0.812672; > b = 0.916541; > c = 0.797810; > sprintf('%.30f', a+b+c) > ans = 2.527023000000000241271891354700 > sprintf('%.30f', c+a+b) > ans = 2.527022999999999797182681504637 > sprintf('%.30f', sum([a,b,c])) > ans = 2.527023000000000241271891354700 > > From this, I'll have to conclude that R's sum() is correct, but probably > internally flipping operands. >
Also check out sumexact in the caTools package. -- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.