Python Line Intersection

Chris Rebert clp2 at rebertia.com
Fri Apr 9 11:44:54 EDT 2010


On Fri, Apr 9, 2010 at 8:04 AM, Peyman Askari <peter_peyman_puk at yahoo.ca> wrote:
>
> Hello
>
> This is partly Python related, although it might end up being more math related.
>
> I am using PyGTK (GUI builder for Python) and I need to find the intersection point for two lines. It is easy to do, even if you only have the four points describing line segments (http://www.maths.abdn.ac.uk/~igc/tch/eg1006/notes/node23.html). However, it requires that you solve for two equations. How can I do this in Python, either solve equations, or calculating intersection points some other way?


Just solve the equations ahead of time by using generic ones.

Given:
y = mx + b
y = nx + c

We set them equal and solve for x:
mx + b = nx + c
mx - nx = c - b
(m-n)x = c - b
x = (c - b) / (m-n)

So we now have a formula for x. y can then be calculated using the
numerical value of x and one of the original formulas for y.
If your equations are not in slope-intercept form, the same approach
works, just use different, appropriate initial equations.

Alternately, you could use a linear algebra library to solve the
system of equations; NumPy sounds like it has at least part of one.
But this is probably overkill for such a simple problem.

Cheers,
Chris
--
Zero is my hero! Squi FTW.
http://blog.rebertia.com



More information about the Python-list mailing list