floating point inaccuracy in Processing

Here is a simple bouncing ball.

The ball seems to lose energy until its peak reaches about 2/3 of the original height. Is this simply a floating point inaccuracy problem?

Changing the values to type double or rounding values fixes the behavior.

Changing the value of gravity to .981 (or a different value) fixes the behavior.

Also, curiously, this problem doesn't occur in Javascript Mode.

Can someone tell me why the ball's height settles at 2/3 of the height? And, why this problem doesn't occur in Javascript Mode?

EDIT: Oops. Initially had .98 commented out...

float ballY=0;
float ballVelocityY=0;

// float gravity=0.981;
float gravity=0.98;

void setup ()
{
  size (400, 400);
  noStroke();
  fill (255, 152, 49);
}

void draw ()
{
  ballVelocityY=ballVelocityY+gravity;
  ballY=ballY+ballVelocityY;

  if (ballY>height)
  {
    println(ballVelocityY);
    ballY=height;
    ballVelocityY=-ballVelocityY;
  }

  background (255);
  ellipse (width/2, ballY, 40, 40);
}
Tagged:

Answers

  • It is due to rounding errors caused by the float data type in these 2 lines

    ballVelocityY=ballVelocityY+gravity;
    ballY=ballY+ballVelocityY;

    The double fixes it because the rounding errors are too small to be noticed.

    Rounding values removes the least significant digits from the number where the errors occur.

    Javascript treats all decimal numbers as doubles

  • Thanks quark! I should have googled float in Javascript....

  • Have you observed the behavior? Doesn't it seem strange that the ball descends every second bounce and then ceases to descend any further?

  • When gravity is 0.98 then the output is

    28.41999
    27.439993
    27.439991
    26.459993
    26.459991
    25.479994
    25.479992
    24.499994
    24.499992
    24.499994
    

    notice that it doesn't always go down or up because rounding errors can be plus or minus.

    When 0.982 the velocity is rock steady!

Sign In or Register to comment.