Floating point numbers have a finite number of precision bits.
Consider this example (in base 10, with 5 fractional digits, for the sake of explaining) where a
is 3.0
:
First case: 1.0 / 3.0 * 3.0
Here the division (1.0 / 3.0) is calculated first, giving you an intermediate value of 0.33333.
Then the multiplication is carried out: 0.33333 * 3 = 0.99999 which is different from 1.0
Second case: 1.0 * 3.0 / 3.0
In this case, the multiplication (1.0 * 3.0) is carried out first, giving an intermediate value of 3.0, which is divided by 3.0, giving you exactly 1.0
Because of this effect, as others have stated, it is not a good idea to compare floating point values exactly with ==
.