Why does setting a const variable (which will be stored with the same value) lead to a different result once divided?
The "issue" is due to the -freciprocal-math
switch (implied by -Ofast
):
Allow the reciprocal of a value to be used instead of dividing by the value if this enables optimizations. For example
x / y
can be replaced withx * (1/y)
, which is useful if(1/y)
is subject to common subexpression elimination. Note that this loses precision and increases the number of flops operating on the value.
The compiler can calculate d = 1/bConst
at compile time and change from:
c/bConst
to
c * d
but multiplication and division are different instructions with different performance and precision.
See: http://coliru.stacked-crooked.com/a/ba9770ec39ec5ac2
You are using -Ofast
in your link, which enables all -O3
optimizations and includes both -ffast-math
, which in turns includes -funsafe-math-optimizations
.
From what I could glean, with optimizations enabled, -funsafe-math-optimizations
allows the compiler to reduce the precision of some computations. This seems to be what happens in the c/bConst
case.