Are floating point operations in C associative?

后端 未结 3 1722
既然无缘
既然无缘 2020-11-28 16:09

Addition mathematically holds the associative property:

(a + b) + c = a + (b + c)

In the general case, this property does not hold for floa

3条回答
  •  天命终不由人
    2020-11-28 17:06

    Floating point multiplication in C is not associative.

    In C, Floating point multiplication is not associative.
    

    Some evidence is with this C code:

    Pick three random float values.
    Check if a*(b*c) is ever not equal to (a*b)*c

    #include
    #include
    #include
    using namespace std;
    int main() {
        int counter = 0;
        srand(time(NULL));
        while(counter++ < 10){
            float a = rand() / 100000;
            float b = rand() / 100000;
            float c = rand() / 100000;
    
            if (a*(b*c) != (a*b)*c){
                printf("Not equal\n");
            }
        }
        printf("DONE");
        return 0;
    }
    

    The program prints:

    Not equal
    Not equal
    Not equal
    Not equal
    DONE
    RUN FINISHED; exit value 0; real time: 10ms; user: 0ms; system: 0ms
    

    Conclusion:

    For my test, three randomly selected floating point multiplication values are associative about 70% of the time.

提交回复
热议问题