0

(libGDX, Java) I'm trying to make an object move from one side of the screen to the other and when it reach the other side it start over. The code I use for the action:

if (position.x < 300) {
position.x -= 1;
}
if (position.x == -70) {
position.x = 131;
}

position is a Vector2. 1 is the movement speed of the object and where I have the problem. The loop work fine if the position.x -= A WHOLE NUMBER, but if I want it to be 0.3f, 1.5f... the loop won't work and the object just continue moving. How can if fix it so that the loop will work with any number?

user3395989
  • 73
  • 1
  • 12

2 Answers2

3

It's so because of the binary representation of floating numbers. Every integer (not too big) has its own representation as a binary number. But 0.3 doesn't have it's accurate representation.

http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm

When comparising floats use:

bool equal(float actual, float expected) {
  return (abs(actual - expected) < 0.000001);
}
user1398619
  • 696
  • 7
  • 8
  • @user3395989 If you want more information, go to [this site](http://www.adambeneschan.com/How-Does-Floating-Point-Work), type in `0.3` and click `float`. – ajb Nov 04 '14 at 18:28
1

You can use Float.floatToIntBits().

Float.floatToIntBits(position.x) == Float.floatToIntBits(-70)

Here another example :

Float fObj1 = new Float("5.35");
Float fObj2 = new Float("5.34");

int i2 = fObj1.compareTo(fObj2);

if(i2 > 0){
  System.out.println("First is grater");
}else if(i2 < 0){
  System.out.println("Second is grater");
}else{
  System.out.println("Both are equal");
}   
Gilberto Ibarra
  • 2,849
  • 2
  • 27
  • 38