# Thread: Very confused over floating points in if-statements

1. ## Very confused over floating points in if-statements

I was working with GLUT, and it was going well until for some inexplicable reason, my logic statement kept failing to... well, to be logical.

I rewrote it for all intents and purposes in a stripped-down program just to test the block itself (as below) and it ends up failing to test true ( x == 1.0f ) on the 10th iteration as it (I think?) should be doing.

I'd appreciate any insight on this, it's confused the heck out of me.

Code:
```#include <iostream>
using namespace std;

int main( void )
{
float x = 0.0f;
for ( float c = 0.0; c < 1; c += 0.1f )
{
x += 0.1f;
cout << "x is: " << x << endl;

// This doesn't test true, even when x == 1
if ( x == 1.0f )
cout << "X hit the contingency.\n";
else cout << "X has not yet hit.\n";
}

system("PAUSE");
return 0;
}```
If you have any thoughts, please don't hesitate to post them. Thanks again.

2. Well, try using double rather than float. Float is quite inaccurate. That can be the reason.

Double is twice as accurate as float is.

3. Logical operators on floating types are something you should avoid . Unfortunately computers have an hard time dealing with these types.

One solution here is to cast when testing it.

Code:
`if ( static_cast<int>(x) == 1 ) // instead of if ( x == 1.0f )`

4. Ok. Thanks again to you both.

5. you could try:

Code:
`for ( float c = 0.0; c != 1; c += 0.1f )`
Some people recommend it.

JOKE! PLEASE DON'T CONTINUE THE DEBATE!

6. >// This doesn't test true, even when x == 1
>if ( x == 1.0f )
Floating-point comparisons for equality are typically doomed to failure due to the imprecision of floating-point. This problem isn't unique to C++; it has to do with the representation of floating-point values. To compare two floating-point values, you do so with a fudge factor:
Code:
```const double fudge = .01; // Or whatever is suitably "small" enough
if ( fabs ( x - 1.0f ) <= fudge )
// Equal (or close enough)```

7. Double is twice as accurate as float is.
Not nessesarily. A double is at least the size of a float, and if one is larger, it will be the double. (floats have at least 6 digis of accuracy.)