简体   繁体   中英

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

Three lines, each containing two space-separated integers

Output Format

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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