Checking to see if 3 points are on the same line

前端 未结 5 1193
天涯浪人
天涯浪人 2020-11-30 08:18

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.

相关标签:
5条回答
  • 2020-11-30 08:57

    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

    0 讨论(0)
  • 2020-11-30 09:03

    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.

    0 讨论(0)
  • 2020-11-30 09:06

    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.

    0 讨论(0)
  • 2020-11-30 09:15

    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.

    0 讨论(0)
  • 2020-11-30 09:17

    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;
    }
    
    0 讨论(0)
提交回复
热议问题