It is often necessary to numerically test whether a point is within a specified polygon or on its border. Here we will develop some functions for this purpose, which might be useful, for example, in problems that compute the electrostatic potential outside systems of electrodes in two dimensions.
The following function evaluates the winding number. The dot products with
{1,}
convert the Cartesian coordinates to the complex numbers needed by Arg. Chop ensures that vanishing winding numbers are returned as 0 instead of a numerically insignificant number. Note that this function is undefined for points that coincide with any of the vertices.
To test this function, we construct a closed polygon with several loops. Selected points are numbered in the diagram. Point 1 is clearly surrounded once in a positive sense, point 2 once in a negative sense, point 3 twice in a negative sense, and point 4 is exterior. Also observe that point 5 is not enclosed while point 6 is encompassed once in a negative sense. As shown below, our function successfully computes these winding numbers.
combines these functions into a single query that returns True for points enclosed by the polygon or on its boundary and False otherwise. If given an open curve, it closes the polygon by connecting the first and last points. The interior and boundary tests are included explicitly so that this function is self-contained.