detecting if doubles are almost equal (in Drill page 124)

12 views
Skip to first unread message

dtopham

unread,
Sep 26, 2009, 11:38:09 AM9/26/09
to PPP-public
Onew of my students came up with this solution:

double first=0; double second=0;
const double delta=1.0/10000000;
cout << "\nEnter two real numbers: ";
cin >> first >> second;
cout << "\ndifference is: " << fabs(first - second)
<< "\n and delta is: " << delta << '\n';
if (fabs(first - second) <= delta)
cout << "\nThe numbers are almost equal\n";
else
cout << "\nThe numbers are not almost equal\n";

but is very surprised at this result:

Enter two real numbers: 1.0000000 1.0000001

difference is: 1e-007
and delta is: 1e-007

The numbers are not almost equal


...seems like a contradiction... I looked in the memory (in debugger)
and see that 1.0000001 is actually stored as
1.0000001000000001, so that explains it, but it is still not
satisfying. Do you have any suggestions on how to write this code so
that it works for this case?

Jay

unread,
Sep 26, 2009, 12:55:16 PM9/26/09
to PPP-public
Not using fabs seems to work.

double first = 0, second = 0;
double const DELTA = 1.0/10000000;

cout <<"Enter two real numbers: ";
cin >> first >> second;

if(first - second <= DELTA)
cout << "almost equal.";
else
cout << "Not almost equal.";

Enter two real numbers: 1.0000000 1.0000001
almost equal.

dtopham

unread,
Sep 26, 2009, 1:16:48 PM9/26/09
to PPP-public
But we need to check both directiosn, right? i.e. I tried this, but
still don't detect almost equal:

if (first > second && (first - second <= delta) ||
second > first && (second - first <= delta))
cout << "\nThe numbers are almost equal\n";
else
cout << "\nThe numbers are not almost equal\n";


Reply all
Reply to author
Forward
0 new messages