In my assignment I had been asked to say why the following code prints mis-match
the code checks for a == square (sqrt(a))
#include <iostream>
#include <cmath>
using namespace std;
#define sqr(x) ((x) * (x))
int main() {
double a = 4.0*atan(1.0); // pi
double b = sqrt(a); // square-root of pi
if (a == sqr(b)) // pi is equal to
// square of square-root of pi?
cout << "Match" << endl;
else
cout << "Mis-Match" << endl;
return 0;
}
I know that this type of problem are do to the fact that floating point numbers are approximate representation and for checking equality one should check for almost equality case i.e. |a-b|<epsilon
,
where epsilon is taken to be 1e-8 or any other suitable value.
But when I replace double
with long double
the code executed to print Match
.
So I want to know when == works and when it does not.