在python中获取正方形边缘的随机点

2024-06-16 08:45:34 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:

给定一个绘图窗口,如何在正方形的周长(绘图窗口的周长)上生成随机点

背景与尝试

关于a rectangle in javascript,我发现了一个类似的问题

我设法编写了一个程序来生成限制范围内的随机点,但问题是如何在随机点位于绘图边缘的条件下找到它们(在这种情况下,x等于5或-5,或者y等于5或-5)

import numpy as np
import matplotlib.pyplot as plt

# Parameters
n = 6 # number of points
a = 5 # upper bound
b = -5 # lower bound

# Random coordinates [b,a) uniform distributed
coordy = (b - a) *  np.random.random_sample((n,)) + a # generate random y
coordx = (b - a) *  np.random.random_sample((n,)) + a # generate random x

# Create limits (x,y)=((-5,5),(-5,5))
plt.xlim((b,a))
plt.ylim((b,a))

# Plot points
for i in range(n):
    plt.plot(coordx[i],coordy[i],'ro')

plt.show()

enter image description here

总结

总之,我的问题是如何生成随机坐标,因为它们位于绘图/画布的边缘。任何建议或帮助都将不胜感激


Tags: sampleinimport绘图asnppltrandom
3条回答

您可以使用它,但这是假设您希望在发现它们不在边缘时丢弃它们

for x in coordx:
    if x != a:
        coordx.pop(x)
    else:
        continue

然后对y做同样的事情

一种可能的方法(尽管不是很优雅)是:将水平点和垂直点分开,假设要在窗口的顶部或底部绘制点。那么

  1. 随机选择y坐标为b或-b
  2. 随机(均匀分布)选择x坐标

类似的方法用于窗口的右边缘和左边缘

希望有帮助

从几何学上讲,处于边缘要求一个点满足某些条件。假设我们讨论的网格的维度由x ~ [0, a]y ~ [0, b]定义:

  • y坐标为0或b,x坐标在[0, a]范围内,或
  • x坐标为0或a,y坐标位于[0, b]

显然有不止一种方法可以做到这一点,但这里有一个简单的方法让你开始

def plot_edges(n_points, x_max, y_max, x_min=0, y_min=0):
    # if x_max - x_min = y_max - y_min, plot a square
    # otherwise, plot a rectangle

    vertical_edge_x = np.random.uniform(x_min, x_max, n_points)
    vertical_edige_y = np.asarray([y_min, y_max])[
        np.random.randint(2, size=n_points)
    ]
    horizontal_edge_x = np.asarray([x_min, x_max])[
        np.random.randint(2, size=n_points)
    ]
    horizontal_edge_y = np.random.uniform(x_min, x_max, n_points)

    # plot generated points
    plt.scatter(vertical_edge_x, vertical_edige_y)
    plt.scatter(horizontal_edge_x, horizontal_edge_y)
    plt.show()

相关问题 更多 >