Possible Duplicate:
Floating point equality in python
I have a small "issue" about my Python code (I use version 2.5 right now, in ika game engine). I currently script objects for my game, and i would like to know, if its safe to compare two floating point number This way:
I will make a short example of what I do currently.
Every objects has a speed, from 0-9, represented in floating points. For example
speed = 4.83 cord_x = 10.0 cord_y = 10.0 They have an AddMovement method. This sets an X,Y value, and represents the goal coordinates for the object.
target_x = 25.0 target_x = 26.75 movement = True # This represents if the object is moveing or not Every frame, the Maximum speed equals to this value:
maximum_x_speed = abs(cord_x-target_x) maximum_y_speed = abs(cord_y-target_y) And the real speed will be:
# Get the real X speed in this frame if maximum_x_speed < speed: real_x_speed = maximum_x_speed else: real_x_speed = speed # Get the real Y speed in this frame if maximum_y_speed < speed: real_y_speed = maximum_y_speed else: real_y_speed = speed Now, based on this real_x_speed value, and real_y_speed value, i substract this value from the coordinates.
if target_x < cord_x: cord_x -= real_x_speed elif target_x > cord_x: cord_x += real_x_speed if target_y < cord_y: cord_y -= real_y_speed elif target_y > cord_y: cord_y += real_y_speed And at the end, i check for equality
if cord_x == target_x and cord_y == target_y: # Halt movement, reached goal movement = False I had floating point errors in the past, with the 0.1 issue, and like... I fear, that this will cause some kind of error. Or this is logically impossible?
If i had grammar mistakes, sorry for them. english is not my native language... I would really appreciate some tips, if i should change this logic, or not.