0
double x1=0.3;
double x2=0.1*3;
cout<<(x1==x2)<<endl;
double y1=0.75;
double y2=0.1*7.5;
cout<<(y1==y2)<<endl;
system("pause");

The output is 0 and 1. I want to know the reason behind it.

  • Well, this is weird. It is quite common to get errors when manipulating doubles in c/c++, due to the way decimal numbers are handled. To put it simply, numbers are stored in a limited memory space. If the number is to big/has too many decimals, the overlapsed data will disapear and you will lose precision. For instance, you would have `1.0001 == 1.0001000...\lots of 0\...09868633` because the computer can't store this level of precision. – Aserre May 21 '14 at 10:26
  • However, you are doing really simple operations, and the result should be equals. What is the output of `x1-x2` and `y1-y2` ? – Aserre May 21 '14 at 10:27
  • Oh, I wish I had more time to answer this. [This recent answer](http://stackoverflow.com/a/23690512/562459) might help a little in the meantime. – Mike Sherrill 'Cat Recall' May 21 '14 at 10:33
  • 2
    possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Pascal Cuoq May 21 '14 at 11:06
  • 1
    @Ploutox No, there is no particular reason why the operation `0.1*3` in the question should be considered simple and produce something equal to `0.3`. `0.1*7.5 == 0.75` may be a consequence of a theorem, seing as `0.75` and `7.5` are both exactly represented, as in http://stackoverflow.com/questions/18031221/rounding-oddity-what-is-special-about-100/18036308#18036308 , but when the hypotheses are so full of special cases, can that even be called a theorem? – Pascal Cuoq May 21 '14 at 11:14
  • 1
    @MikeSherrill'CatRecall' You can always answer the fourteen or so duplicate that are sure to come up in the coming week. If the essence of your answer is limited to “Never compare floating point numbers for equality”, however, you can also let the million of other, equally superstitious StackOverflow users answer it in your place. – Pascal Cuoq May 21 '14 at 11:17
  • The essence of my answer is, "Follow the guidance in the C FAQ." – Mike Sherrill 'Cat Recall' May 21 '14 at 12:25

0 Answers0