Bool Camparision

Why d return true but e return false?
1
2
3
4
5
  int main() {
 bool d = .06 == .2*.3;
 bool e = .3  == .1 + .1 + .1;
    cout << d << endl << e;
}
Because floating point numbers are approximations. You may want to check this out: https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/02Numerics/Double/paper.pdf
I know float is approximation so with that d should be false too?
Not necessarily, perhaps on your system .2 and .3 have opposite but equal errors. Try printing each of those constants (with a high precision) and see what they print.

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    double f = .2;
    double e = .3 ;
    double g = .1 + .1 + .1;

    cout << fixed << setprecision(20);
    cout << e << " " << f << endl;
    cout << g << endl;
    cout << f + e << endl;

    return 0;
}


output:
1
2
3
0.29999999999999998890 0.20000000000000001110
0.30000000000000004441
0.50000000000000000000


This is why you should never compare floating point numbers for equality and your compiler should be able to warn you about these issues.

Jim
Topic archived. No new replies allowed.