Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking to see if 3 points are on the same line

Tags:

pseudocode

I want to know a piece of a code which can actually tell me if 3 points in a 2D space are on the same line or not. A pseudo-code is also sufficient but Python is better.

like image 514
Hossein Avatar asked Sep 28 '10 14:09

Hossein


People also ask

How do you check if three points are on the same line?

Three points are collinear if the value of the area of the triangle formed by the three points is zero. Substitute the coordinates of the given three points in the area of the triangle formula. If the result for the area of the triangle is zero, then the given points are said to be collinear.

How do you check if all the points are in same line?

From any point in the list (e.g. first one) if all other points have the same slope with that one, then they are on the same line.


2 Answers

You can check if the area of the ABC triangle is 0:

[ Ax * (By - Cy) + Bx * (Cy - Ay) + Cx * (Ay - By) ] / 2 

Of course, you don't actually need to divide by 2.

like image 73
florin Avatar answered Sep 18 '22 21:09

florin


This is C++, but you can adapt it to python:

bool collinear(int x1, int y1, int x2, int y2, int x3, int y3) {   return (y1 - y2) * (x1 - x3) == (y1 - y3) * (x1 - x2); } 

Basically, we are checking that the slopes between point 1 and point 2 and point 1 and point 3 match. Slope is change in y divided by change in x, so we have:

y1 - y2     y1 - y3 -------  =  -------- x1 - x2     x1 - x3 

Cross multiplying gives (y1 - y2) * (x1 - x3) == (y1 - y3) * (x1 - x2);

Note, if you are using doubles, you can check against an epsilon:

bool collinear(double x1, double y1, double x2, double y2, double x3, double y3) {   return fabs((y1 - y2) * (x1 - x3) - (y1 - y3) * (x1 - x2)) <= 1e-9; } 
like image 29
dcp Avatar answered Sep 18 '22 21:09

dcp