Skip to content

Blog Post

Point-in-Polygon: Ray Casting vs Winding Number

How do you decide whether a point lies inside a polygon? Two classic algorithms, ray casting (even–odd) and the winding number, compared: how they work, where they differ, and a short Python implementation.

Algorithms

Given a polygon and a point, is the point inside or outside? It sounds like a trivial question, but it sits behind a surprising amount of everyday software: clicking on a country in a map, deciding which cadastral parcel a GPS point belongs to, hit-testing shapes in a drawing program, selecting the mesh elements that fall inside a region, or filtering survey points by a boundary. It is also the natural next step after computing the area of a polygon with the Shoelace formula: the same vertex list, the same cross products, a different question.

Two algorithms dominate: ray casting (the even–odd rule) and the winding number. They give the same answer for ordinary simple polygons, and differ in interesting ways for everything else. This article explains both, compares them, and gives a short Python implementation of each.

The problem

A polygon is given by its vertices $P_1, P_2, \dots, P_n$ in order, and the boundary is the closed chain of edges $P_1P_2, P_2P_3, \dots, P_nP_1$. For a query point $p = (p_x, p_y)$ we want to decide whether it is inside. For a convex polygon you can simply test that $p$ lies on the same side of every edge, but polygons from real data are usually concave, so we need something more general. Both methods below work for any polygon and take $O(n)$ time, with no preprocessing.

Ray casting (the even–odd rule)

Draw a ray from $p$ in any fixed direction, usually the positive $x$ direction, and count how many times it crosses the boundary. Every time the ray crosses the boundary it passes from inside to outside or the other way round. Since the ray ends up infinitely far away, which is certainly outside, an odd number of crossings means $p$ started inside and an even number means it started outside.

1 2 3 P 3 crossings · odd → inside 1 2 Q 2 crossings · even → outside
Figure 1. A U-shaped polygon. The ray from P crosses the boundary 3 times (odd), so P is inside. The ray from Q, which sits in the notch, crosses it twice (even), so Q is outside.

The crossing test

For the edge from $(x_1, y_1)$ to $(x_2, y_2)$, the ray from $p$ to the right crosses it when two conditions hold:

  1. the edge straddles the ray's height: one endpoint is above $p_y$ and the other is not, written $(y_1 > p_y) \ne (y_2 > p_y)$;
  2. the crossing point lies to the right of $p$:
$$ p_x < x_1 + \frac{(p_y - y_1)\,(x_2 - x_1)}{y_2 - y_1} $$

The first condition uses a half-open rule: a vertex at exactly the height of the ray counts as being below it. This one convention takes care of the nasty special cases. A horizontal edge never straddles anything, so it is ignored. When the ray passes exactly through a vertex, the two edges meeting there are counted once if the boundary really passes from one side to the other, and zero or two times if it merely touches the ray, which is exactly what parity needs. Division by zero cannot happen, because $y_1 \ne y_2$ whenever the straddle test succeeds.

The winding number

The winding number $w$ counts how many times the boundary winds around the point: walk once around the polygon and count the net number of full turns, counterclockwise as positive. For a simple polygon, $w = \pm 1$ inside (the sign depends on the orientation of the vertices) and $w = 0$ outside. The point is inside when $w \ne 0$.

The definition can be written directly with angles. Let $a_i = P_i - p$ be the vector from the point to vertex $i$; then

$$ w = \frac{1}{2\pi}\sum_{i=1}^{n} \operatorname{atan2}\!\big(a_i \times a_{i+1},\; a_i \cdot a_{i+1}\big) $$

where each term is the signed angle swept by the edge as seen from $p$. This is easy to understand but slow and sensitive to rounding, because it uses an inverse trigonometric function per edge. A much better way to compute the same integer is to count signed crossings of the same ray that ray casting uses:

  • an edge going upward across the ray with $p$ on its left adds $+1$;
  • an edge going downward across the ray with $p$ on its right subtracts $1$.

Whether $p$ is left or right of an edge is decided by the sign of a cross product, the same quantity that appears in the Shoelace formula and in the convexity test of that article:

$$ \text{side} = (x_2 - x_1)(p_y - y_1) - (p_x - x_1)(y_2 - y_1), \qquad \text{side} > 0 \;\Rightarrow\; p \text{ is left of the edge} $$

The result is an exact integer computed from additions, multiplications and comparisons only, with no square roots, trigonometry or division.

Where they differ

For a simple polygon, the two methods always agree. The difference appears when the boundary crosses itself, the classic example being the five-pointed star drawn in one stroke (a pentagram). The central pentagon is enclosed twice by the boundary:

Even–odd rule centre: 2 crossings → outside
Winding number centre: w = 2 → inside
Figure 2. The same self-intersecting star under the two rules. The ray from the centre crosses the boundary twice (even, so outside), while the boundary winds around the centre twice ($w = 2$, so inside).

Neither answer is "wrong": they are two different definitions of what the interior of a self-intersecting outline is. You meet them every day as the two fill rules of vector graphics: SVG and HTML canvas have fill-rule="evenodd" and fill-rule="nonzero", and the figure above was drawn with exactly those two settings.

Ray casting (even–odd)Winding number (non-zero)
Simple polygonCorrectCorrect
Self-intersecting polygonRegions covered an even number of times are outsideAny region the boundary winds around is inside
HolesAdd the hole as another ring; it just worksAdd the hole with the opposite orientation
Depends on vertex orientationNoOnly the sign of $w$, not whether it is zero
Cost$O(n)$, one division per crossing edge$O(n)$, multiplications and comparisons only

For ordinary, well-formed polygons, such as parcels, administrative boundaries or building footprints, either is fine. Choose the winding number when you want the interior of overlapping or self-touching rings to behave like a filled shape, and the even–odd rule when overlapping areas should cancel out, as when a hole is described by simply nesting a ring inside another.

Implementation in Python

Both functions take a point $(x, y)$ and a list of vertices, and loop once over the edges. They use the conventions explained above: the half-open straddle test and the same horizontal ray to the right.

def ray_casting(p, poly):
    """Even-odd rule: True if p is inside the polygon (list of (x, y) vertices)."""
    x, y = p
    inside = False
    for i in range(len(poly)):
        x1, y1 = poly[i]
        x2, y2 = poly[(i + 1) % len(poly)]
        if (y1 > y) != (y2 > y):                        # the edge straddles the ray's height
            x_cross = x1 + (y - y1) * (x2 - x1) / (y2 - y1)
            if x < x_cross:                             # ... and crosses to the right of p
                inside = not inside
    return inside


def winding_number(p, poly):
    """Winding number of the polygon around p (0 means outside)."""
    x, y = p
    wn = 0
    for i in range(len(poly)):
        x1, y1 = poly[i]
        x2, y2 = poly[(i + 1) % len(poly)]
        side = (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1)   # > 0: p is left of the edge
        if y1 <= y:
            if y2 > y and side > 0:                     # upward edge with p on its left
                wn += 1
        elif y2 <= y and side < 0:                      # downward edge with p on its right
            wn -= 1
    return wn


if __name__ == "__main__":
    u_shape = [(1, 1), (9, 1), (9, 7), (6, 7), (6, 3.5), (4, 3.5), (4, 7), (1, 7)]
    for name, pt in (("P", (2, 5)), ("Q", (5, 5)), ("R", (11, 2))):
        print(name, ray_casting(pt, u_shape), winding_number(pt, u_shape))

    import math
    star = [(math.cos(math.radians(90 + 144 * k)), math.sin(math.radians(90 + 144 * k))) for k in range(5)]
    print("star centre", ray_casting((0, 0), star), winding_number((0, 0), star))

Running it prints:

P True 1
Q False 0
R False 0
star centre False 2

P is inside the U-shape, Q (in the notch) and R (far to the right) are outside, and the star's centre shows the disagreement between the two rules.

Practical notes

  • Points on the boundary. Both algorithms give an arbitrary answer for a point lying exactly on an edge or vertex. If that case matters, test it explicitly first: the point is on an edge when the cross product above is zero and the point lies within the edge's bounding box. Then decide whether the boundary counts as inside.
  • Floating-point robustness. Points very close to an edge can be misclassified by rounding. If your input is integer or fixed-point data, do the arithmetic in integers: the winding-number version needs no division, so it can be made exact. For anything critical, use a library with robust predicates.
  • Speed with many points. First reject points outside the polygon's bounding box, which is cheap and removes most of them. For many polygons or many queries, use a spatial index such as an R-tree or a grid, or a library such as Shapely or matplotlib.path.Path.contains_points, rather than looping in Python.
  • Convex polygons. You can do better than $O(n)$: for a convex polygon with vertices in order, a binary search over the fan of triangles from one vertex answers in $O(\log n)$.
  • Geographic coordinates. Latitude and longitude are not planar. For small areas, project the polygon and the point first (for example, with the EGSA87 converter for Greek data), and be careful with polygons that cross the ±180° meridian.

Summary

  • Ray casting counts crossings of a ray from the point: odd means inside.
  • The winding number counts signed crossings of the same ray (or the net number of turns): non-zero means inside.
  • They agree for simple polygons and differ for self-intersecting ones, just like the evenodd and nonzero fill rules in SVG.
  • Both are short, $O(n)$ and easy to implement; handle boundary points and rounding explicitly if they matter.
Share LinkedIn

Keep reading

Related articles

Searching...