Originally posted by float
View Post
Suppose you want to calculate a^4 and you write the following fragment:
Code:
double a = ...; double x = a * a * a * a;
Another way to calculate a^4 is this:
Code:
double a = ... double x = a * a; x = x * x;
If you use -ffast-math, this is what the compiler would optimize the first code fragment to.
You would think they would yield the same result, but they don't in some cases.
Floating point numbers are not exact, they have limited precision, so each multiplication operation has to round the result a little bit.
In the first fragment, each multiplication will have some rounding error.
In the second fragment, the first multiplication will have some rounding error and it will be carried over into the second multiplication, which would have additional rounding error.
Thus, the rounding errors will be slightly different. The 2 code fragments would produce slightly different results in the least significant bits.
Most programs would not care about the minimal floating point rounding errors, and would be fine with this optimization, for those programs -ffast-math is appropriate.
Comment