trouble comparing if float values are equal

Previous topic - Next topic

BdR

Hi all, I have a question. I want to have a bullet follow a path from a start position to a goal position in a certain nr of steps. And when it reaches the goal position, it should do a hit check etc. But I can't get the compare of 2 floating point values to work. Here is an example code.
Code (glbasic) Select

SEEDRND GETTIMERALL()
WHILE (KEY(0) = FALSE)
  DEBUG " -- start test --\n"
  Test()
WEND

FUNCTION Test:

  // variables
  LOCAL iStep%, iCount%
  LOCAL x#, y#, xGoal#, yGoal#, xSpeed#, ySpeed#

  // start at bottom of screen
  x = 320
  y = 480
 
  // goal is random position at top of screen
  xGoal = RND(640)
  yGoal = RND(100)

  // set speed so that block moves from start to end in exactly 60 steps
  xSpeed = (xGoal - x) / 60.0
  ySpeed = (yGoal - y) / 60.0

  // do the steps
  iCount = 0
  WHILE (iCount < 100)

    // draw block and goal
    DRAWRECT xGoal, yGoal, 4, 4, RGB(192, 255, 0)
    DRAWRECT x, y, 8, 8, RGB(0, 192, 255)
    SHOWSCREEN

    // update all
    x = x + xSpeed
    y = y + ySpeed
   
    IF (x = xGoal) AND (y = yGoal)
      DEBUG "GOAL REACHED!\n"
    ELSE
      // goal not reached, check if close to goal
      IF (ABS(x - xGoal) < 10) AND (ABS(y - yGoal) < 10)
        DEBUG "Positions are NOT equal. x=" + x + " y=" + y + " <> xGoal=" + xGoal + " yGoal=" + yGoal + "\n"
      ENDIF
    ENDIF

    iCount = iCount + 1 // to stop WHILE loop
  WEND

ENDFUNCTION

So the code does the following:
1) divide length of path into 60 steps
2) increment start position with steps of divided length
3) check if goal position is reached

The check if x=xGoal and y=yGoal is almost never true (on rare occasions it is). I guess this is due to limited precision of floating points, causing the end result to being slightly off. For example the goal position is (123, 456) but the incremented result is (123.0003, 456.0001) or something like that. So I think you will run into the same problem when working with C or Java etc. not just GLBasic.

But it's strange because the debug output is for example this
Positions are NOT equal. x=116 y=34 <> xGoal=116 yGoal=34

I can add an iSteps variable and simply count the nr of steps. But my question is, what is the best way to check if the goal is reached using float variables?

KidPaddle

Code (glbasic) Select
IF (ABS(Value1 - Value2) < 0.001) ....
is a valid solution. ABS returns only unsigned part of a value, and if difference lesser than 0.001, you count this as the same.

Regards
Thomas
Intel CoreDuo 6300, GT 7950 512MB, 2 GB Ram, XP SP2
GP2X MK1, Firmware 2.0.0

MrTAToad

I had a routine in th Maths section that allows comparing floating point values within a specific tolerance.