3

a=99.0 cout<<(1.0/a*a==1.0) give 0

while

cout<<(1*a/a==1.0) give 1 and cout<<(1.0/99.0*99.0==1.0) also give 1

what's the rationale behind them??? why I change the order of the variables or when I change it to real number, the outcome will change?

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
Kelvin Ng
  • 31
  • 1
  • 1
    @PaulMcKenzie is absolutely correct! These are known issues with floats and doubles: [What Every Programmer Should Know About Floating-Point Arithmetic](http://floating-point-gui.de/basic/) – geipel Dec 18 '16 at 06:45
  • 2
    @geipel Those are not _issues_. It's how floating points are defined and work. The fact that they don't work as you expect doesn't mean that they are flawed. Maybe the expectations were wrong and that's all. – skypjack Dec 18 '16 at 07:00
  • 1
    @skypjack: You are correct that this just how IEEE 754 works. I was agreeing with the statement that use of == operator (on calculated float values) is generally problematic. – geipel Dec 18 '16 at 07:10

1 Answers1

1

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 ==.

foolo
  • 804
  • 12
  • 22