How can I check if a point is below a line or not ?
I've the following data:
Line [ {x1,y1}, {x2,y2} ]
Points {xA,yA}, {xB,yB} ...
I need to write a small algorithm in python to detect points on one side and the other side of the line.
thanks
How can I check if a point is below a line or not ?
I've the following data:
Line [ {x1,y1}, {x2,y2} ]
Points {xA,yA}, {xB,yB} ...
I need to write a small algorithm in python to detect points on one side and the other side of the line.
thanks
You could try using a cross product -- http://en.wikipedia.org/wiki/Cross_product.
v1 = {x2-x1, y2-y1} # Vector 1
v2 = {x2-xA, y2-yA} # Vector 1
xp = v1.x*v2.y - v1.y*v2.x # Cross product
if xp > 0:
print 'on one side'
elif xp < 0:
print 'on the other'
else:
print 'on the same line!'
You'd need to calibrate what each side is. If you want it to be "below" or "above" you need to ensure the points on the line are sorted horizontally.
I haven't tested this.
Edit I initially put in the dot product formula. :o
Luckily I found http://stackoverflow.com/questions/243945/calculating-a-2d-vectors-cross-product.
Lets say you've given 2 points A, B and you want to know in which halfplane a third point C lies. The terms "below" and "above" as criteria are very vague, so you need a reference point, for example the origin. Just be sure this reference point is not collinear with A and B.
What you have now is a triangle (A, B, C). Using the determinant you can calculate the signed area (see here, or here). The only interesting thing here is to remember the sign.
Next step: for a given point D calculate the signed area of the triangle (A, B, D). If the result has the same sign as the area of your reference triangle -> C and D are on the same side of (A, B). If the sign differs -> C and D lie on opposite sides of the line. If the area of (A, B, D) is 0 then A, B and D are collinear. Note: use the Python builtin cmp
to compare the triangle areas.