A bug with float in VC6.0???

Started by
6 comments, last by Slug 19 years, 1 month ago
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???
Advertisement
This is normal. Read up on floating-point arithmetic here.
1.49012e-008 is quite the same as 0. This is due to floating point impersicion.
"C lets you shoot yourself in the foot rather easily. C++ allows you to reuse the bullet!"
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...
Quote:Original post by Slug
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...

if(g_Alpha < 0.0f)     g_Alpha = 0.0f;
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.
Quote:Original post by Slug
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...


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!

This topic is closed to new replies.

Advertisement