簡體   English   中英

如何在 python 中生成一組二維點,其中任何點都在至少一個其他點的 R 單位內

[英]How to generate a set of 2D points in python where any point is within R units of at least one other point

例如,如果我有點 A、B 和 C,歐幾里得距離

這意味着 A 至少在一個鄰居的 R 單位內。

這里已經生成了一個初始點,然后嘗試使用隨機 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

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM