How to find out if a point lie in rectangle?

2.8k Views Asked by At

I have a rectangle in $2D$ space which is determined by $2$ points (each in opposite vertice) $p_1(x,y)$ and $p_2(x,y)$ . How can I find out numerically if a other point $p(x,y)$ is lying inside plane of the rectangle?

2

There are 2 best solutions below

5
On BEST ANSWER

Suppose
Left-Top vertex is $P_1(x_1,y_1)$, and
Right-Bottom vertex is $P_2(x_2,y_2)$
(in general, $2$ opposite vertices).

Point $P(x,y)$ is lying inside the rectangle, if

$$ \min\{x_1,x_2\} < x < \max\{x_1,x_2\} $$ $$ and $$ $$ \min\{y_1,y_2\} < y < \max\{y_1,y_2\}. $$


If $x_1<x_2$, and $y_1<y_2$ (Left-Bottom and Right-Top vertices), then $$ x_1<x<x_2 $$ $$ and $$ $$ y_1<y<y_2. $$


If edges of rectangle aren't parallel to coordinate axes, then $2$ points can't define unique rectangle (see image):
point $P$ belongs to blue rectangle, but not belongs to red rectangle.

enter image description here


Update (case of non-parallel to coordinate axes edges)

Points $P_1$ and $P_2$ determines diagonal of possible rectangle. Other vertices are on the circle (circumference) with diameter $P_1P_2$:

enter image description here

So, if $P$ is inside the circle with diameter $P_1P_2$, then it is possible to build such rectangle, that $P$ belongs to rectangle.

Denote
radius of the circle: $R = \dfrac{1}{2}\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}$;
center of the circle: $x_o = \frac{x_1+x_2}{2}$, $y_o = \frac{y_1+y_2}{2}$,

Condition of possibility to build such rectangle: $$ (x-x_o)^2 + (y-y_o)^2 < R^2. $$

0
On

I think this is what you are looking for:

if $p_1(x,y)$ and $p_2(x,y)$ determine a rectangle ($p_1(x) \ne p_2(x) \wedge p_1(y) \ne p_2(y)$) then the other point, $p(x,y)$, will be inside the rectangle if and only if $p(x)$ is between $p_1(x)$ and $p_2(x)$ and $p(y)$ is between $p_1(y)$ and $p_2(y)$.