[1]


Task

Find the point of intersection of two lines in 2D.



The 1st line passes though    (4,0)    and    (6,10) .

The 2nd line passes though    (0,3)    and    (10,7) .




' version 16-08-2017
' compile with: fbc -s console
#Define NaN 0 / 0   ' FreeBASIC returns -1.#IND
 
Type _point_
    As Double x, y
End Type
 
Function l_l_intersect(s1 As _point_, e1 As _point_, s2 As _point_, e2 As _point_) As _point_
 
    Dim As Double a1 = e1.y - s1.y
    Dim As Double b1 = s1.x - e1.x
    Dim As Double c1 = a1 * s1.x + b1 * s1.y
    Dim As Double a2 = e2.y - s2.y
    Dim As Double b2 = s2.x - e2.x
    Dim As Double c2 = a2 * s2.x + b2 * s2.y
    Dim As Double det = a1 * b2 - a2 * b1
 
    If det = 0 Then
        Return Type(NaN, NaN)
    Else
        Return Type((b2 * c1 - b1 * c2) / det, (a1 * c2 - a2 * c1) / det)
    End If
 
End Function
 
' ------=< MAIN >=------
 
Dim As _point_ s1, e1, s2, e2, answer
 
s1.x = 4.0 : s1.y = 0.0 : e1.x =  6.0 : e1.y = 10.0  ' start and end of first line
s2.x = 0.0 : s2.y = 3.0 : e2.x = 10.0 : e2.y =  7.0  ' start and end of second line
answer = l_l_intersect(s1, e1, s2, e2)
Print answer.x, answer.y
 
s1.x = 0.0 : s1.y = 0.0 : e1.x =  0.0 : e1.y =  0.0  ' start and end of first line
s2.x = 0.0 : s2.y = 3.0 : e2.x = 10.0 : e2.y =  7.0  ' start and end of second line
answer = l_l_intersect(s1, e1, s2, e2)
Print answer.x, answer.y
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End