0

Consider following piece of code:

#include <iostream>
using namespace std;

int main() {
    double x = 1.77;
    double y = 1.76;

    double diff = x-y;
    cout << "x-y = " << diff << endl;
    if (diff <= 0.01)
    {
        cout << "x and y differ by less than 1.0/100 ..." << endl;
    }
    return 0;
}

Following output I am getting:

x-y = 0.01

But I don't see the print x and y differ by less than 1.0/100... which is expected here because difference between x and y is 0.01.

Pravar Jawalekar
  • 605
  • 1
  • 6
  • 18
  • https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – stark Mar 26 '20 at 01:40
  • 2
    You'll be surprised to learn that the difference is not 0.01. Not in C++, not in any modern computer programming language that uses the common floating point format and algorithms. This is because floating point math is broken, it was always broken and it will always be broken. See the linked question for more information. – Sam Varshavchik Mar 26 '20 at 01:41
  • The actual difference is actually [very slightly greater than `0.01`](http://coliru.stacked-crooked.com/a/978724a3003dd28e). – Miles Budnek Mar 26 '20 at 01:42
  • https://floating-point-gui.de/ – axiac Mar 26 '20 at 01:46

0 Answers0