0

I have a problem with the method where I am comparing floats, since it returns bad data:

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
    Care to describe more about the problem and what have you tried to solve it? – Harshil Sharma Mar 15 '17 at 14:44
  • 1
    Have you tried `0.1+0.1+0.1 == 0.3`? It returns `False` ;) –  Mar 15 '17 at 14:45
  • Two floats can have different values, and yet still look the same when you print them. This is because the string representation of floats tends to round off so that it doesn't display dozens of digits after the decimal point when a shorter approximation is good enough. It's possible that you're actually comparing 0.1 to 0.1000001, where of course the former is less than the latter. – Kevin Mar 15 '17 at 14:46
  • You are probably running into floating point imprecision. That said, `0.100000 < 0.100000` does not `return True`. – Chris_Rands Mar 15 '17 at 14:46
  • 4
    Possible duplicate of [What is the best way to compare floats for almost-equality in Python?](http://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python) – pbaranay Mar 15 '17 at 14:46
  • 1
    @Chris_Rands how do you know you have `0.100000`? Printing the value will truncate it. – Peter Wood Mar 15 '17 at 14:48
  • @PeterWood Both values are truncated exactly the same of course and so one is not deemed less than the other. Anyway, I think we're digressing from the point.. – Chris_Rands Mar 15 '17 at 14:51
  • 2
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – 001 Mar 15 '17 at 14:51
  • @Chris_Rands I'm not digressing. When you say `0.100000` is the value it's not the value. You think that's air you're breathing? – Peter Wood Mar 15 '17 at 15:47

1 Answers1

0

I checked the links given in comments and I got to the point, that while it's not the most beautiful way to do it for Python 2.7, it works.

Someone gave a simple solution, where you can change to floats to strings and then compare them (which is well enough for the algorithm I'm testing).

Here is how it could look like:

    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)