Reputation: 11753
Suppose now I have a straight line in the 2D coordinate system, which can be wrote as:
ax+by+c=0
Now I have a point, whose coordinate is (x0,y0)
, and my question is how I can tell the relative position of the point with regard to the line (above or below). One solution I can figure out is as follows:
// set up the line
a = ..;
b = ..;
c = ..;
// make sure that b is negative
if (b>0)
{
a = -a;
b = -b;
c= -c;
}
// set the point
x0 = ..;
y0 = ..;
temp = a*x0+b*y0+c;
if (temp<0)
// the point is above the line
else
// the point is under the line.
In the above codes I did not consider the special case of straight line (horizontal or vertical), but the basic idea is to make sure b
is negative first, and then calculate the function's value (temp
), and depending on its value determine the point's position. I am not sure whether this is a good solution. Any ideas will be appreciated.
Upvotes: 2
Views: 2423
Reputation: 80197
Yes, your solution is right. Possible optimization - don't negate coefficients, just evaluate sign of expression b*(a*x+b*y+c)
. + for above, - for under, 0 for points on line and for indefinite case - vertical lines.
Explanation: common line equation
a*x+b*y+c=0
may be transformed to normal equation
x*cos(t)+y*sin(t)-p=0
(with division by -sign(c)*Sqrt(a^2+b^2)
)
where p is the length of normal to line from coordinate origin (O), t is angle between OX axis and this normal.
The sign of expression
XX*cos(t)+YY*sin(t)-p=0
is positive, when point (XX, YY) and coordinate origin are divided by this line, and negative otherwise. So for t in range 0..Pi sin is positive, and positive value of expression denotes that point is above the line (origin is under) and so on...
Upvotes: 3
Reputation: 31290
Corrected version
You don't have to invert any signs. Simply inserting the coordinates of the point (x,y)
into the form of the line ax + by + c
results in a value, call this h
.
Also, compute d = -c/b
. If h
and d
have the same sign and if 'd > 0', then (x,y)
is "below".
bool isBelow( double a, double b, double c, double x0, double y0 ){
double d = -c/b;
if( d == 0 ){
return -a/b*x0 > y0;
} else {
double h0 = a*x0 + b*y0 + c;
return d > 0 && (d > 0 == h0 > 0);
}
}
It will also work for for horizontal lines, but not for vertical lines (where b==0
).
Upvotes: 2