[R] Bug or feature? sum(c(a, b, c)) != (a + b + c)
Gabor Grothendieck
ggrothendieck at gmail.com
Wed Aug 24 01:00:30 CEST 2011
On Tue, Aug 23, 2011 at 6:56 PM, Daniel Lai <danlai at 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
More information about the R-help
mailing list