Addition mathematically holds the associative property:
(a + b) + c = a + (b + c)
In the general case, this property does not hold for floa
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.