【发布时间】:2012-10-11 12:01:23
【问题描述】:
我的 Python 代码有一个小“问题”(我现在在 ika 游戏引擎中使用 2.5 版)。我目前为我的游戏编写对象,我想知道比较两个浮点数是否安全这种方式:
我将做一个简短的例子来说明我目前的工作。
每个对象都有一个速度,从 0 到 9,以浮点数表示。例如
speed = 4.83
cord_x = 10.0
cord_y = 10.0
他们有一个 AddMovement 方法。这会设置 X、Y 值,并表示对象的目标坐标。
target_x = 25.0
target_x = 26.75
movement = True # This represents if the object is moveing or not
每一帧,最大速度等于这个值:
maximum_x_speed = abs(cord_x-target_x)
maximum_y_speed = abs(cord_y-target_y)
而真正的速度是:
# 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
现在,根据这个 real_x_speed 值和 real_y_speed 值,我从坐标中减去这个值。
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
最后,我检查是否相等
if cord_x == target_x and cord_y == target_y:
# Halt movement, reached goal
movement = False
我过去曾遇到过浮点错误,例如 0.1 问题,并且……我担心这会导致某种错误。或者这在逻辑上是不可能的?
如果我有语法错误,对不起。英语不是我的母语... 如果我应该改变这个逻辑,我真的很感激一些提示。
【问题讨论】:
-
什么是“0.1”问题?您是浮点错误、异常还是在您认为应该的时候说两个认为不相等?
-
两个东西不相等。前段时间我有一个案例,当我将 0.1 加在一起 10 次时,并检查它是否等于 1.0。
标签: python