如何使用Python / Numpy从八边形中均匀地随机采样2D点?我们可以说八边形以原点(0, 0)为中心。以下是我所做的:
上述代码大部分是正确的,但是max_radii的计算是错误的,因为边缘略微向外弯曲。 我并不一定要坚持上述算法的整体方法,所以任何算法都可以。话虽如此,我稍微倾向于一种方法(如果上述方法实际上能正确运行的话),它可以推广到16边形等等。
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');
上述代码大部分是正确的,但是max_radii的计算是错误的,因为边缘略微向外弯曲。 我并不一定要坚持上述算法的整体方法,所以任何算法都可以。话虽如此,我稍微倾向于一种方法(如果上述方法实际上能正确运行的话),它可以推广到16边形等等。