How to get a random point on the interior of an irregular polygon? [closed]

I would do this in three steps:

  1. Create a list of triangles that cover the same area as the polygon you are given. If your polygon is convex it is easier, since you can have all triangles share a common vertex. If your polygons are not guaranteed to be convex, then you’ll have to find a better polygon triangulation technique. Here’s the relevant Wikipedia article.

  2. Randomly choose which triangle to use, weighted by its area. So if triangle A is 75% of the area and triangle B is 25% of the area, triangle A should be picked 75% of the time and B 25%. This means find the fraction of the total area that each triangle takes up, and store that in a list. Then generate a random double number from 0 – 1 (Math.random() does this), and subtract each value in the list until the next subtraction would make it negative. That will pick a triangle at random with the area weights considered.

  3. Randomly pick a point within the chosen triangle. You can use this formula : sample random point in triangle.

Alternatively, you can pick a rectangle that covers the entire polygon (such as its bounding box) and randomly pick a point within that rectangle. Then check if the point is inside the polygon, and if it isn’t then generate a new random point and try again, repeating as necessary. Theoretically this could take forever, but in practice it should take four or five tries at most.

You still need to have an algorithm to determine if the point is inside the polygon though. If you already have it broken up into triangles this is easier, just check if it’s in any of those.

Leave a Comment