Skip to content
Prev 269490 / 398503 Next

Bug or feature? sum(c(a, b, c)) != (a + b + c)

On Tue, Aug 23, 2011 at 8:17 PM, Daniel Lai <danlai at bccrc.ca> wrote:
Its probably to do with the order of summations. With your a,b,c you get:

 > (a+b+c) == (c+b+a)
 [1] TRUE
 > (a+b+c) == (c+a+b)
 [1] FALSE

shock horror, addition is not associative[1]. Lets investigate:

 > sum(c(a,b,c)) == c+a+b
 [1] TRUE
 > sum(c(a,b,c)) == a+c+b
 [1] TRUE

 'sum' seems to get the same answer as adding the first and the third,
then adding the second - explicitly:

 > sum(c(a,b,c)) == (a+c)+b
 [1] TRUE

I'm not sure what it would do for four values in the sum. Have fun
finding out. Does matlab similarly have a+b+c != c+b+a?

Barry

[1] or commutative or distributive or one of those -ives you learn one
day in school. Too lazy to wikipedia it right now...