(Python)确定(x,y)坐标是否共线的脚本 - 获取一些错误 [英] (Python) Script to determine if (x, y) coordinates are colinear - getting some errors

查看:930
本文介绍了(Python)确定(x,y)坐标是否共线的脚本 - 获取一些错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像标题所说,我试图编写一个程序,该程序需要一个(x,y)坐标列表,并确定是否有3个点共线(位于具有相同斜率的线上)

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)

我收到了一些错误消息。就目前而言,我得到一个TypeError:'int'对象不是可供订阅的消息。如果我将共线性测试调用的部分取出在areCollinear函数中,则会出现索引超出范围错误。我是python新手,只是想学习。

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)

错误讯息:

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


推荐答案

(p0,p1,p2):更简单和更稳定的函数来测试三点的共线性:

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

(请注意,最好不要硬编码epsilon,它相对于矢量的长度。)

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

这篇关于(Python)确定(x,y)坐标是否共线的脚本 - 获取一些错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆