Python比较浮点数

时间:2017-03-15 14:43:06

标签: python

我对比较浮点数的方法有问题,因为它返回错误的数据:

0.100000< 0.100000 = True

def check_potential_field(current, squares):
  if len(squares) == 0:
    return False
  for square in squares:
    distance = math.sqrt(math.pow(current.x - square.x, 2) + math.pow(current.y - square.y, 2))
    if distance < current.current_distance:
        print "%f < %f = True" % (distance, current.current_distance)
        return True
  return False

1 个答案:

答案 0 :(得分:0)

我检查了评论中给出的链接,我明白了,虽然它不是Python 2.7最美妙的方式,但它可以工作。

有人提供了一个简单的解决方案,您可以将浮点数更改为字符串然后进行比较(这对于我测试的算法来说已经足够了。)

以下是它的样子:

    def check_potential_field(self, square):
       distance = math.sqrt(math.pow(self.x - square.x, 2) + math.pow(self.y - square.y, 2))
       return str(distance) < str(self.current_distance)