## How to check if a point is inside a rectangle

A rectangle

I’ve just found this interesting question on StackExchange:

If you have a rectangle ABCD and point P. Is P inside ABCD?

## The idea

The idea how to solve this problem is simply beautiful.

If the point is in the rectangle, it divides it into four rectangles:

Divided rectangle

If P is not inside of ABCD, you end up with somethink like this:

Point is outside of rectangle

You might note that the area of the four triangles in is bigger than the area of the rectangle. So if the area is bigger, you know that the point is outside of the rectangle.

## Formulae

If you know the coordinates of the points, you can calculate the area of the rectangle like this:

$$A_\text{rectangle} = \frac{1}{2} \left| (y_{A}-y_{C})\cdot(x_{D}-x_{B}) + (y_{B}-y_{D})\cdot(x_{A}-x_{C})\right|$$

The area of a triangle is:
$$A_\text{triangle} = \frac{1}{2} (x_1(y_2-y_3) + x_2(y_3-y_1) + x_3(y_1-y_2))$$

## Python

def isPinRectangle(r, P):
"""
r: A list of four points, each has a x- and a y- coordinate
P: A point
"""

areaRectangle = 0.5*abs(
#                 y_A      y_C      x_D      x_B
(r[0][1]-r[2][1])*(r[3][0]-r[1][0])
#                  y_B     y_D       x_A     x_C
+ (r[1][1]-r[3][1])*(r[0][0]-r[2][0])
)

ABP = 0.5*(
r[0][0]*(r[1][1]-r[2][1])
+r[1][0]*(r[2][1]-r[0][1])
+r[2][0]*(r[0][1]-r[1][1])
)
BCP = 0.5*(
r[1][0]*(r[2][1]-r[3][1])
+r[2][0]*(r[3][1]-r[1][1])
+r[3][0]*(r[1][1]-r[2][1])
)
CDP = 0.5*(
r[2][0]*(r[3][1]-r[0][1])
+r[3][0]*(r[0][1]-r[2][1])
+r[0][0]*(r[2][1]-r[3][1])
)
DAP = 0.5*(
r[3][0]*(r[0][1]-r[1][1])
+r[0][0]*(r[1][1]-r[3][1])
+r[1][0]*(r[3][1]-r[0][1])
)
return areaRectangle == (ABP+BCP+CDP+DAP)