# A bug with float in VC6.0???

This topic is 4821 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi everyone, now listen, that is strange... I'm trying to do semothing like that: //Declaration float g_Alpha; //Init. g_Alpha = 0.3f //error //g_Alpha = 0.1f //no error now, suppose i want to inc., or dec that value by 0.1 when i press a key ... case 107: if(g_Alpha < 1.0f) g_Alpha += 0.1f; break; case 109: if(g_Alpha > 0.0f) g_Alpha -= 0.1f; break; ... so, if i init the float g_alpha with 0.1f, all will work ok, but if i init it with 0.3f or 0.5f, alpha will have a wrong value when sub. 0.1f of g_Alpha when he is equal to 0.1f. g_Alpha will have the value 1.49012e-008 instead of 0. Did I missed something???

##### Share on other sites
This is normal. Read up on floating-point arithmetic here.

##### Share on other sites
1.49012e-008 is quite the same as 0. This is due to floating point impersicion.

##### Share on other sites
How can i correct that?

if i write

if(g_Alpha > 0.0f)
g_Alpha -= 0.1f;

then g_Alpha will be set to -0.1 when this situation occur...

##### Share on other sites
Quote:
 Original post by SlugHow can i correct that?if i writeif(g_Alpha > 0.0f)g_Alpha -= 0.1f;then g_Alpha will be set to -0.1 when this situation occur...

if(g_Alpha < 0.0f)     g_Alpha = 0.0f;

##### Share on other sites
read the link posted, floating point numbers have roundoff /trunctation errors, especially when trying to represent decimal numbers ...

you would be surprised to know that 0.1 CANNOT be respresented correctly in a floating point number. So you are really adding / subtracting a number slightly bigger or smaller than you think you are.

##### Share on other sites
Quote:
 Original post by SlugHow can i correct that?if i writeif(g_Alpha > 0.0f)g_Alpha -= 0.1f;then g_Alpha will be set to -0.1 when this situation occur...

you could use an epsilon value

static const float fEpsilon = 0.001f; // change this depending on precision                                      // desired...if( g_Alpha < EPSILON)    g_Alpha = 0.0f;// or use it to see if two floating point values are close enough to each // otherif( fabs( g_Alpha - someFloat) < EPSILON) ){  // handle the situation however you want....}

hth

Ok, thxn a lot!

• 10
• 17
• 9
• 14
• 41