你可以使用
random
库在极坐标中进行随机采样。先采样一个方向,然后再采样一个径向距离。在下面的示例中,我选择方向在
[0, 2*pi]
上均匀分布,半径则是以用户输入的平均值和标准差为参数的正态分布。
import random
import math
def generate_points(center_x, center_y, mean_radius, sigma_radius, num_points):
points = []
for i in range(num_points):
theta = random.uniform(0, 2*math.pi)
radius = random.gauss(mean_radius, sigma_radius)
x = center_x + radius * math.cos(theta)
y = center_y + radius * math.sin(theta)
points.append([x,y])
return points
作为如何调用它的示例。
>>> generate_points(5.0, 7.0, 1.0, 0.1, 8)
[[4.4478263120757875, 6.018608023032151],
[4.407825651072504, 6.294849028359581],
[5.0570272843718085, 6.17834681191539],
[5.307793789416231, 6.156715230672773],
[4.368508167422119, 7.712616387293795],
[5.327972045495855, 5.917733119760926],
[5.748935178651789, 6.437863588580371],
[3.9312163910881033, 6.388093041756519]]
如果您希望点按特定顺序绕组,则可以使用类似于
numpy.linspace
的方法,以顺时针或逆时针方式遍历样本角度。例如:
import random
import math
import numpy as np
def generate_points(center_x, center_y, mean_radius, sigma_radius, num_points):
points = []
for theta in np.linspace(0, 2*math.pi - (2*math.pi/num_points), num_points):
radius = random.gauss(mean_radius, sigma_radius)
x = center_x + radius * math.cos(theta)
y = center_y + radius * math.sin(theta)
points.append([x,y])
return points
如果您不想安装numpy
,您可以编写自己类似的版本linspace
def linspace(start, stop, num_steps):
values = []
delta = (stop - start) / num_steps
for i in range(num_steps):
values.append(start + i * delta)
return values