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.
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.
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).
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
)
one example
a = 1e-30 b = 1e+30 c = -1e+30
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With