简体   繁体   中英

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

which means than A is within R units from at least one neighbor.

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.

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

Num points = 1000
Minimal Euclidean Distance = 0.22933741053890785
Maximum Euclidean Distance = 4.999991431695809

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM