我想过滤numpy.random.choice
生成的结果。我要解决的问题无法通过首先使用np.where
并随机选择条件来解决。通常,我希望所有随机选择的元素中都包含一些属性。
此问题的特殊情况是,我想随机选择一个平面中的n
个点,以便任何给定的点对至少相距d
个距离。我不确定这是否可以在多项式时间内完成,因为这个问题看起来像是NP完全集团问题。
如果无法获得所需的点数,则应使用较低的d
重复该算法。
答案 0 :(得分:0)
一种直接的方法是逐点生成数组并检查每个新点是否符合您的条件。这是您的方法:
import math
import random
# We define a distance function
def distance(x1, y1, x2, y2):
return math.sqrt((x2-x1)**2+(y2-1)**2)
# We define a function that checks if a new point respects the distance condition
def distance_respected(points, dist_max, new_x, new_y):
distance_respected = True
for point in points:
if distance(point[0], point[1], new_x, new_y)>dist_max:
distance_respected = False
return distance_respected
# In the following example I decided to just consider part of a plane. More precisely
# [-10,10]*[-10,10]
number_of_points = 5
max_distance = 2
points = []
for point in range(number_of_points):
# random.uniform() generates a random float between our two numbers
new_x = random.uniform(-10,10)
new_y = random.uniform(-10,10)
while not distance_respected(points, max_distance, new_x, new_y):
new_x = random.uniform(-10,10)
new_y = random.uniform(-10,10)
points.append((new_x, new_y))
输出:
[(-3.425486982794177, -5.415726177177236),
(-4.109629395121301, -0.8693732638893792),
(-2.2778596980094257, 1.1101779439932162),
(-3.0579069964130916, 1.2909258679375473),
(-3.067639560760325, 1.1507562378468599)]
答案 1 :(得分:-1)
Poisson disc sampling对此很有用。运行时与NP-complete完全不同。
该算法基本上是“保留一系列热点,并选择附近的其他热点。如果几次尝试都找不到附近的热点,则将其永久冷却。”
您将需要四叉树(或类似的树)来提高附近点的查找效率。