Problem dealing with float numbers

Started by
8 comments, last by landlocked 12 years, 9 months ago
Okay so Im making a physics engine for circles

and Im doing the following code to check whenever an object is resting




if ( (Velocity.x - 0.000001f <= 0.01f && Velocity.x - 0.000001f >= -0.002f)
&& (Velocity.y - 0.000001f <= 0.01f && Velocity.y - 0.000001f >= -0.002f) )
{
State = ABOUT_TO_DIE;
Velocity = Vector2(0.0f);
}



the thing is not all of my objects go through that if even when in the simulation they clearly seem to be resting..

a quick debug shows this...

x = -1.3607700e-008
y = 0.33765292


at first I thought I was dealing with some kind NaN value but a quick _isnan(Velocity.x) showed me that this is not the case

so Im out of ideas of what that value mean and what to do
Advertisement
I have no idea what your math is supposed to accomplish, but I suspect that what you want is this:

if(abs(Velocity.x) < 0.001f && abs(Velocity.y) < 0.001f)
{
// ... foo ...
}

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

I'm not sure why you expect it to go through that code if y is 0.33765292.
Oh yeah youre right I guess I was too focused on the [color=#1C2837][size=2]-1.3607700e-008 issue
[color=#1C2837][size=2]

[color=#1C2837][size=2]any ideas what does this mean?
It's scientific notation; the 'e' means "times ten to the power of..."

So your number is -1.37077 x 10^-8, which is to say -0.0000000137077.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

thank you

any quick way to clamp these exponential values and approximate them to 0 without breaking the physics?
Yes. It's in my first reply to this thread.

If you really want "true 0" then you can do this:

float clamp(float invalue)
{
static const float epsilon_ = 0.0001f; // Ideally share this globally and use it instead of magic numbers

if(abs(invalue) < epsilon_)
return 0.0f;

return invalue;
}


But that is NOT smart. You should never do equality checks on floating point numbers, so using an epsilon comparison is the right thing to do anyways... and I already posted the code for that above.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

floats are not precision data types, what about double or int ?

Never say Never, Because Never comes too soon. - ryan20fun

Disclaimer: Each post of mine is intended as an attempt of helping and/or bringing some meaningfull insight to the topic at hand. Due to my nature, my good intentions will not always be plainly visible. I apologise in advance and assure you I mean no harm and do not intend to insult anyone.

doubles aren't precise, either, you know...

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Yarr decimal data type :P
Always strive to be better than yourself.

This topic is closed to new replies.

Advertisement