Double imprecision

I’m having trouble with some physics code. When the user presses an arrow key, it adds/subtracts 0.25 to the character’s x velocity. Then the world steps, which should add/subtract 0.05 to get it closer to 0. This output of the velocity for each step shows what went wrong:

0.0 //Not moving
0.25 //Pushed arrow key
0.45 //Held arrow key some more + game subtracted 0.05
0.4 //Subtracted 0.05
0.35000000000000003 //Subtracted 0.05
0.30000000000000004
0.25000000000000006
0.45000000000000007 //added 25, subtracted 0.04
0.4000000000000001

This gets things confused and the character will keep creeping along slowly in the same direction, while going through things it would normally collide with.
What might be wrong?

Rounding to 2 decimal places would work, but I want to see if there is a better way first.

When I jump, sometimes my feet get stuck in the ground, I’m assuming that’s a related problem.

This is standard behaviour. Accurate floating point operations are really expensive, so the CPU only approximates them. This is why you get the added error. As long as you are never checking for an exact value (i.e. dblVal == 0.35) you can typically live with it.

You could use integers instead. Multiply all values (say by 100) so you can emulate the decimal values you need. When you use the value you convert to a double and divide back down by 100.

Second (and you might want to check if there is anything in the API that will do this already) you could build your own equals function where it takes an error value. I’m thinking something like:


public static boolean dblEquals(double a, double b, double error)
{
    return (a+error) > b && (a-error) < b;
}

dblEquals( a, b, 0.0001 );

I don’t think 0.05 can actually be accurately represented as a float either. Dividing 1.0 by various powers-of-two and their combinations thereof should be accurately represented up to a point (no pun intended).

Cas :slight_smile:

The main problem was that once the velocity got down to 0.049999999… it would get reduced to a number slightly under 0. The code would assume that it was a negative multiple of 0.05 and therefore add 0.05 to it to get it back to 0, thus going back to 0.49999999999999… again and creating an infinite loop.

Using an int instead sounds like a good idea.

Rather then adding 0.5 if the value is less then 0, why not add 0.5 if the value is less then -0.00001 ? You could also round values after making lots of add/removes to the nearest 0.05.