0

I write below program but My program cannot check the two number is equal or not. There is no error, I would be appreciate for any help.

import math
def IsCollinding(ball1,ball2):
  distance=math.sqrt((((ball2[0]-ball1[0])**2)+((ball2[1]-ball1[1])**2)))
  print(type(distance))
  print(type(ball1[2]+ball2[2]))
  if(distance==ball1[2]+ball2[2]):
    print("Is Coliding")
  else:
    print("Not Coliding")
  print(distance)
  print(ball1[2]+ball2[2])
ball1=[2,2,3]
ball2=[11,11,9.7279220614]
IsCollinding(ball1,ball2)

output:

<type 'float'>
<type 'float'>
Not Coliding
12.7279220614
12.7279220614

1 Answers1

6

You can not really do this. Floats may appear equal, but are actually different due to floating point precision. However, you can cheat. We can call two numbers "equal" if the difference between the two is very small.

The function looks like this:

(x - y) < delta

Where delta is a small number. Implemented in Python:

def almost_equal(x, y, delta=1e-10):
    return abs(x - y) < delta

I use abs here to get the absolute value of the difference. We avoid having to deal with negative numbers and the order of the x and y arguments this way.

Comparing two floats is one of the most common gotchas, and is something most of us run into at one point. Googling "comparing two floats python" should have returned plenty of informative results about this topic.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96