简体   繁体   English

如何检查笛卡尔坐标中的三个点在 python 中是否共线?

[英]How to check three points in cartesian coordinates are collinear in python?

Three lines, each containing two space-separated integers三行,每行包含两个空格分隔的整数

Output Format Output 格式

Print True if those three points are collinear and False otherwise

Ok, I know how to start...好的,我知道如何开始...

for i in range(3):
    x, y = list(map(int, input().split()))
    if x >= 1000:
        print()
    elif y >= 1000:
        print()
    elif x <= -1000:
        print()
    elif y <= -1000:
        print()
    else:

One can turn three points into a trio of vectors between the possible pairs.可以将三个点变成可能对之间的三个向量。 Those three points are colinear iff the resulting vectors are parallel.如果结果向量是平行的,那么这三个点是共线的。 Two vectors are parallel iff their dot product is equal to +- the product of their magnitudes.两个向量是平行的,如果它们的点积等于 +- 它们大小的乘积。

Thus, one way to determine if three points are parallel is to first compute the vectors between them, then to take the dot product of those vectors.因此,确定三个点是否平行的一种方法是首先计算它们之间的向量,然后取这些向量的点积。 Turns out you don't need every single pairwise vector, you just need one pair for each point.事实证明,您不需要每个成对向量,每个点只需要一对。

Assuming that your data is in a file "data.csv" , so that "Three lines, each containing two space-separated integers", the following would work:假设您的数据位于文件"data.csv"中,因此“三行,每行包含两个空格分隔的整数”,以下将起作用:

import numpy as np

#read in the data
data = np.genfromtxt("data.csv")
#get vectors between adjacent points in the data matrix
vecs = np.diff(data, axis=0)
#get the magnitudes of the vectors in the vector matrix
magnitudes = np.sqrt(np.sum(vecs**2, axis=-1))
#and the products of the magnitudes of adjacent vectors in the vector matrix
magnitude_products = magnitudes[1:]*magnitudes[:-1]
#and the dot products of adjacent vectors in the vector matrix
dot_products = np.sum(vecs[1:]*vecs[:-1], axis=-1)
#check if those two things are the same size, disregarding the sign.
are_colinear = np.allclose(np.abs(magnitude_products), np.abs(dot_products))

This will work for any number of points in any number of dimensions.这将适用于任意数量的维度中的任意数量的点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM