(1) I understand that integer addition is associative, for example (res1 & res always produce the same result)
int i1, i2, i3;
int res1 = i1 + i2 + i3;
int res2 = i1 + (i2 + i3);
(2) I also understand that rounding error may occur in the following case
float f = ...;
int i1, i2, i3;
float res = f + i1 + i2 + i3 ; // rounding error may occur in `float + int`
(Question) What I want to know is, in the following code, could res1 & res2 always produce the same result (no rounding error)?
float f = ...;
int i1, i2, i3;
float res1 = f + i1 + i2 + i3;
float res2 = f + (i1 + i2 + i3); // use associativity of integer addition
This code:
prints:
when
floatis IEEE-754 binary32 and round-to-nearest is used.On the other end, this code:
prints: