Hossein
Hossein

Reputation: 41961

Checking to see if 3 points are on the same line

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.

Upvotes: 39

Views: 56920

Answers (5)

dcp
dcp

Reputation: 55467

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;
}

Upvotes: 66

Douglas
Douglas

Reputation: 37781

Read this, and use it to find the equation of a line through the first two points. Follow the instructions to find m and b. Then for your third point, calculate mx + b - y. If the result is zero, the third point is on the same line as the first two.

Upvotes: 0

Rob Vermeulen
Rob Vermeulen

Reputation: 1970

Rule 1: In any linear 2d space, two points are always on the same line.

Take 2 points and build an equation that represents a line through them. Then check if the third point is also on that line.

Good luck.

Upvotes: -1

florin
florin

Reputation: 14346

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.

Upvotes: 85

Dimitris Leventeas
Dimitris Leventeas

Reputation: 1702

y - y0 = a(x-x0) (1) while a = (y1 - y0)/(x1 - x0) and A(x0, y0) B(x1, y1) C(x2, y2). See whether C statisfies (1). You just replace the appropriate values.

Details

Upvotes: 0

Related Questions