floating-pointrounding-errorassociativity

Could rounding error occurs in the addition between float and an associative addition of integer?


(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

Solution

  • This code:

    #include <stdio.h>
    
    
    int main(void)
    {
        float f = 0x1p25f;
        int i1 = 1, i2 = 1, i3 = 1;
        printf("%.99g\n", f + i1 + i2 + i3);
        printf("%.99g\n", f + (i1 + i2 + i3));
    }
    

    prints:

    33554432
    33554436
    

    when float is IEEE-754 binary32 and round-to-nearest is used.

    On the other end, this code:

    #include <stdio.h>
    
    
    int main(void)
    {
        float f = 0x1p-24f;
        int i1 = 1, i2 = -1, i3 = 0;
        printf("%.99g\n", f + i1 + i2 + i3);
        printf("%.99g\n", f + (i1 + i2 + i3));
    }
    

    prints:

    0
    5.9604644775390625e-08