简体   繁体   中英

Identification of the intersection point of two lines

Here are the calculations

L1 = Line joining points A(x1,y1) and B(x2,y2) L2 = Line joining points c(x3,y3) and D(x4,y4)

For Line L1

Line Equation : y = m1*x + c1

slope m1 : (y2-y1)/(x2-x1)

Y intercept : c1 = (y1 - m1*x1)

For Line L2

Line Equation : y = m2*x + c2

slope m2 : (y4-y3)/(x4-x3)

Y intercept : c2 = (y3 - m2*x3)

For Point of Intersection

Solving the above equations we get

x = (c2 -c1)/(m1-m2)

y = (c1*m2 - c2*m1)/(m2-m1)

These above calculations are used to calculate the intersection points in my java program.

The Problem

The problem occurs when the two lines are parallel to x-axis and y-axis respectively. For example if the connecting points are as follows

L1 = A(34,112) B(34,180) ...(x-coordinate value remains constant)

L2 = C(72,100) D(88,100) ...(y-coordinate value remains constant)

now m1 will become Infinity and m2 will become 0 accordingly c1 will become Infinity and c2=y3 as a result the computation of the intersection points using below given formula gives strange (NaN) result although the lines L1 and L2 must meet at (34,100).

x = (c2 -c1)/(m1-m2)

y = (c1*m2 - c2*m1)/(m2-m1)

Why such a problem ? How is this problem handled using math so that it can be implemented in the program.

A line which is parallel to the y-axis cannot be expressed as y = ax + b . You need to use the general equation of a line ax + by + c = 0 . Determine the coefficients of the equations of your two lines and solve the linear system of their intersection. Make sure the determinant of the system is different from 0, otherwise there is no solution, or an infinity (which you can consider being another case of no solution).

You can obtain a and b coefficients quite easily considering the normal vector of your segment (if vect(AB) = (x,y) then normal(AB) = (-y,x) = (a,b) . You then determine c by introducing the coordinates of A in the equation : c = -a*x_A - b*y_A .

You now have a linear system to solve :

(S) : { a1*x + b1*y + c1 = 0    
      { a2*x + b2*y + c2 = 0

If det = a1*b2 - a2*b1 = 0 (be careful with loss of precision, make your comparison epsilon-wise), then the system has no unic solution. Otherwise, you can find the inverse of the matrix of the system :

M = (a1  b1), M^(-1) = 1/det * ( b2  -b1) 
    (a2  b2)                   (-a2   a1) 

Now you just need to compute

M^(-1) * (-c1) = 1/det * (-b2*c1 + b1*c2)
         (-c2)           ( a2*c1 - a1*c2)

And that's it, you have your solution !

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