Tuesday, 16 April 2019

best practices on floating point precision in python

Earlier tonight, a friend of mine just handed me this cute problem. The problem says:

Make a program in MATLAB to check whether a point is inside a triangle or not. Not to forget to check if the point is on the border as well. Triangle points are x=(0,0),y=(0,1)andz=(1,0)

The problem is not hard to solve. The idea is to find the equation of the hypotenuse and check if the point lies on any leg of the triangle. Check for inside and outside turns out not to be that difficult, however.

I made the code on MATLAB, the logic seems to be fine. But the problem is that the result are not in a harmony with that logic! I started questioning my code since I am not such skillful in MATLAB. Nevertheless, I gave it a try on my preferred language, Python.

Here is my code:


def isInsideTriangle(x,y):
    if  x == 0 or y == 0 or y ==  1-x:
        print('on the border of the triangle')
    elif x > 1 or y > 1 or x < 0 or y < 0 or y > 1-x:
            print('outside of the triangle')
            print(1-x)  # check the value
    else:
        # verbose these values to double check
        print(1-x)
        print(y)
        print(type(y))
        print(type(1-x))
        print(y==(1-x))
        print('inside of the triangle')

isInsideTriangle(0.2,0.8)

When trying with this two values, the result on console shall be on the border. However, the program said it is inside! I tried to switch between x and y i.e. isInsideTriangle(0.8,0.2) but the program outputted the expected result this time.

This leaded me to realize that there is no thing to do with the logic but with floating-point precision. I increased the size of the variables on MATLAB to be 64 bit precision and the program works fine.

My question now

As a Python guy, what are the best programming practices to avoid such problems in Python? How can we avoid such annoying problems specially in production environments?



from best practices on floating point precision in python

No comments:

Post a Comment