Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associativity math: (a + b) + c != a + (b + c)

Recently I was going through an old blog post by Eric Lippert in which, while writing about associativity he mentions that in C#, (a + b) + c is not equivalent to a + (b + c) for certain values of a, b, c.

I am not able to figure out for what types and range of arithmetic values might that hold true and why.

like image 523
Vaibhav Singla Avatar asked Aug 14 '15 07:08

Vaibhav Singla


People also ask

How do you solve associativity?

The formula for the associative property of multiplication is (a × b) × c = a × (b × c). This formula tells us that no matter how the brackets are placed in a multiplication expression, the product of the numbers remains the same.

What is the associative property of a/b c?

The associative property states that when adding or multiplying, the grouping symbols can be relocated without affecting the result. The formula for addition states (a+b)+c=a+(b+c) and the formula for multiplication states (a×b)×c=a×(b×c).


2 Answers

On the range of the double type:

double dbl1 = (double.MinValue + double.MaxValue) + double.MaxValue; double dbl2 = double.MinValue + (double.MaxValue + double.MaxValue); 

The first one is double.MaxValue, the second one is double.Infinity

On the precision of the double type:

double dbl1 = (double.MinValue + double.MaxValue) + double.Epsilon; double dbl2 = double.MinValue + (double.MaxValue + double.Epsilon); 

Now dbl1 == double.Epsilon, while dbl2 == 0.

And on literally reading the question :-)

In checked mode:

checked {     int i1 = (int.MinValue + int.MaxValue) + int.MaxValue; } 

i1 is int.MaxValue

checked {     int temp = int.MaxValue;     int i2 = int.MinValue + (temp + temp); } 

(note the use of the temp variable, otherwise the compiler will give an error directly... Technically even this would be a different result :-) Compiles correctly vs doesn't compile)

this throws an OverflowException... The results are different :-) (int.MaxValue vs Exception)

like image 167
xanatos Avatar answered Oct 04 '22 10:10

xanatos


one example

a = 1e-30 b = 1e+30 c = -1e+30 
like image 39
Luka Rahne Avatar answered Oct 04 '22 09:10

Luka Rahne