How do I randomly sample 2d points uniformly from within an octagon using Python / Numpy? We can say that the octagon is centered at the origin (0, 0). The following is what I've done:
import numpy as np
import matplotlib.pyplot as plt
def sample_within_octagon(num_points):
points = np.zeros((num_points, 2))
# Generate random angle in radians
angles = np.random.uniform(0, 2 * np.pi, size=(num_points,))
# Calculate the maximum radius for the given angle
# This is wrong.
max_radii = 1.0 / np.sqrt(2) / np.cos(np.pi / 8 - angles % (np.pi / 4))
# Generate random radius within the bounds of the octagon
# Use square-root to prevent it from being more dense in center.
radii = np.sqrt(np.random.uniform(0, max_radii))
# Convert polar coordinates to Cartesian coordinates
x = radii * np.cos(angles)
y = radii * np.sin(angles)
points[:, 0] = x
points[:, 1] = y
return points
num_points = 10000
random_points = sample_within_octagon(num_points)
plt.scatter(
np.array(random_points)[:, 0],
np.array(random_points)[:, 1], s=1);
plt.axis('equal');
The above code is mostly correct, but the max_radii calculation is incorrect, because the edges are slightly curved outward.
I am not necessarily committed to the overall approach of the above algorithm, so any algorithm will do. Having said that, I would slightly prefer an approach that (like the above, if it had actually worked correctly) would generalize to 16-gons and so on.