Next / Previous / Contents / Shipman's homepage

14.3. Line.intersect(): Find the intersection of two lines

homcoord.py
# - - -   L i n e . i n t e r s e c t

    def intersect(self, other):
        '''Where do lines self and other intersect?
        '''

The first step is to insure that the lines actually intersect. For two lines with these equations:

The lines have the same slope if:

homcoord.py
        #-- 1 --
        # [ if self and other have the same slope ->
        #     raise ValueError
        #   else -> I ]
        if self.a * other.b == other.a * self.b:
            raise ValueError("Lines have the same slope.")

Finding the intersection of the lines is done by treating the two lines as a system of two simultaneous equations in two variables. The NumPy package has a solver, linalg.solve. The arguments to this function are a square array of the coefficients and a vector of the constants; the result is a vector containing the coordinates of the intersection.

First we rewrite the formulae to move the constants to the right of the equal sign:

Recasting it in matrix form:

homcoord.py
        #-- 2 --
        # [ x, y  :=  solution to the simultaneous linear equations
        #       (self.a * x + self.b * y = -self.c) and
        #       (other.a * x + other.b * y = -other.c) ]
        a = num.array ( ( (self.a, self.b), (other.a, other.b) ) )
        b = num.array ( (-self.c, -other.c) )
        x, y = num.linalg.solve(a,b)

        #-- 3 --
        return Pt(x, y)