Are floating point operations in C associative?

后端 未结 3 1695
既然无缘
既然无缘 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:07

    You can make floating point operations associative with the gcc options:

    -funsafe-math-optimizations -O2
    

    Example:

    double test (double a, double b, double c) {    
      return (a + b + c) * (a + (b + c));
    }
    

    This is reduced to:

    double temp = a + (b + c);
    return temp * temp;
    

    Similarly, (a + b + c) - (a + (b + c)) is reduced to zero, ignoring the possibility of INF and NAN.

    If I compile with -fassociative-math -O2 instead, I get the weird message:

    warning: -fassociative-math disabled; other options take precedence

    The -funsafe-math-optimizations can improve speed if you don't care about the order of the operands anyway, but it may cause loss of precision if the order of operands is important, and you may lose NAN and INF results.

提交回复
热议问题