News:

*NEW* Current Version on STEAM16.793

Webchat:
Visit the chat

trouble comparing if float values are equal

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()WENDFUNCTION 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  WENDENDFUNCTION`
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?

` IF (ABS(Value1 - Value2) < 0.001) ....`