[英]How to generate a set of 2D points in python where any point is within R units of at least one other point
Eg if I have points A,B and C, the euclidean distance例如,如果我有点 A、B 和 C,欧几里得距离
which means than A is within R units from at least one neighbor.这意味着 A 至少在一个邻居的 R 单位内。
Here a have generated an initial point and from there a try to generate the next one within the euclidean distance using the random function.这里已经生成了一个初始点,然后尝试使用随机 function 在欧几里得距离内生成下一个点。
import random
import math
import matplotlib.pyplot as plt
euclideanR = 5
NUMPOINTS = 1000
SPACEMIN = -30
SPACEMAX = 30
# Euclidean distance
def distance(p, q):
return math.sqrt((q[0]-p[0])**2 + (q[1]-p[1])**2)
# try new point
def calc_new(points):
x1 = points[0]
y1 = points[1]
# help the function place the next point
x2 = x1-2*abs(euclideanR)*random.random()+euclideanR
y2 = y1-2*abs(euclideanR)*random.random()+euclideanR
return (x2,y2)
# generate first point in this space range
x0 = random.randint(SPACEMIN, SPACEMAX)
y0 = random.randint(SPACEMIN, SPACEMAX)
points2D = [(x0, y0)]
dist_list = []
while len(points2D) < NUMPOINTS:
q = random.choice(points2D)
p = calc_new(q)
d = distance(q, p)
if d < euclideanR:
dist_list.append(d)
points2D.append(p)
print("Num points = {}".format(len(points2D)))
print("Minimal Euclidean Distance = {}".format(min(dist_list)))
print("Maximum Euclidean Distance = {}".format(max(dist_list)))
x, y = list(zip(*points2D))
fig = plt.figure()
plt.scatter(x, y)
plt.title("distanceR = {}, #points = {}, Init_space=[{},{}]".
format(euclideanR, NUMPOINTS, SPACEMIN, SPACEMAX))
plt.show()
Output Output
Num points = 1000
Minimal Euclidean Distance = 0.22933741053890785
Maximum Euclidean Distance = 4.999991431695809
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.