0

Your program is nt behaving as wat u expect where sometimes it output the correct and at times incorrect result. During debugging,u manage to locate the problem to the following statement.
A/b == c
Where a,b,c are using the ieee 754 floating point representation and where the value c is generate in an earlier arithmetic statement in the program. The statement return a false although u expect the left hand side to ne similar to the right side. Why this problem occurs n how to solve it

Edited by angelineang

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by geojia
0

Read this http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html and look at the section Rounding Error.

Play around with this

#include <iostream>
#include <iomanip>
#include <cmath>
// Might need this later
#include <cfloat>
using namespace std;
int main(){
   //   a   /   b   =  c  =  c
   // (1/9) / (1/3) = 3/9 = 1/3
   float a(1.0f/9.0f),b(1.0f/3.0f),c(1.0f/3.0f);
   // Check to see if equal
   if ( a/b == c )
      cout << "Equal: " << fixed << setprecision(15) 
           << "a/b = " << a/b << " c = " << c << endl;
   else
      cout << "Not equal: " << fixed << setprecision(15) 
           << "a/b = " << a/b << " c = " << c << endl;
   return 0;
}

Output :

$ ./a.out
Not equal: a/b = 0.333333313465118 c = 0.333333343267441
0

Not an expert: but instead of checking for equivalence why not check for difference less than some val (1e-8)?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.