How can I find the general form equation of a line from two points?

前端 未结 5 1956
野的像风
野的像风 2021-02-02 09:48

Given the input:

double x1,y1,x2,y2;

How can I find the general form equation (double a,b,c where ax + b

5条回答
  •  被撕碎了的回忆
    2021-02-02 10:16

    If you start from the equation of defining line from 2 points

    (x - x1)/(x2 - x1) = (y - y1)/(y2 - y1)
    

    you can end up with the next equation

    x(y2 - y1) - y(x2 - x1) - x1*y2 + y1*x2 = 0
    

    so the coefficients will be:

    • a = y2 - y1
    • b = -(x2 - x1) = x1 - x2
    • c = y1*x2 - x1*y2

    My implementation of the algorithm in C

    inline v3 LineEquationFrom2Points(v2 P1, v2 P2) {
        v3 Result;
    
        Result.A = P2.y - P1.y;
        Result.B = -(P2.x - P1.x);
        Result.C = P1.y * P2.x - P1.x * P2.y;
    
        return(Result);
    }
    

提交回复
热议问题