Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Python) Script to determine if (x, y) coordinates are colinear - getting some errors

like the title says, I'm trying to write a program that takes a list of (x, y) coordinates, and determines if any 3 points are collinear (lie on a line with the same slope)

I'm getting some error messages. As it stands, I get an "TypeError: 'int' object is not subscriptable" message. If I take out the part where collinearityTest calls on the areCollinear function, I get an "index out of range" error. I'm new to python, and just trying to learn.

def areCollinear(p1, p2, p3):
    slope1 = (p2[1] - p1[1]) / (p2[0] - p1[0])
    slope2 = (p3[1] - p2[1]) / (p3[0] - p2[0])
    if slope1 == slope2:
        print "Points are colinear"
    else:
        print "Points are NOT colinear, what's the matter with you?"

def collinearityTest(pointList):
    position = 0
    while position >=0 and position < len(pointList):

        for p1 in pointList[position]:
            position = position + 1
            for p2 in pointList[position]:
                position = position + 1
                for p3 in pointList[position]:
                    position = position + 1
                    areCollinear(p1, p2, p3)

pointList = [(10, 20), (55, 18), (10, -45.5), (90, 34), (-34, -67), (10, 99)]

collinearityTest(pointList)

ERROR MESSAGE:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 23, in <module>
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 19, in collinearityTest
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 2, in areCollinear
    if __name__ == '__main__':
TypeError: 'int' object is not subscriptable
like image 926
user1246457 Avatar asked Nov 28 '22 17:11

user1246457


1 Answers

Here's an easier and numerically more robust and stable function to test the collinearity of three points:

def collinear(p0, p1, p2):
    x1, y1 = p1[0] - p0[0], p1[1] - p0[1]
    x2, y2 = p2[0] - p0[0], p2[1] - p0[1]
    return abs(x1 * y2 - x2 * y1) < 1e-12

(Note that it would be best not to hard-code the epsilon, and to make it relative to the length of the vectors.)

like image 81
Sven Marnach Avatar answered Dec 06 '22 17:12

Sven Marnach