简体   繁体   English

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

[英]Get random points at edges of a square in python

Question问题

Given a plotting window, how does one generate random points at the perimeter of a square (perimeter of the plotting window)?给定一个绘图 window,如何在正方形的周边(绘图窗口的周边)生成随机点?

Background and attempt背景和尝试

I found a similar question with regards to a rectangle in javascript .在 javascript 中发现了一个关于矩形的类似问题。

I managed to write a program to generate random points within limits but the question is regarding how one could find random points with the condition that they are at the edge of the plot (either x is equal to 5 or -5,or y is equal to 5 or -5 in this case).我设法编写了一个程序来生成限制内的随机点,但问题是如何找到随机点,条件是它们位于 plot 的边缘(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()

在此处输入图像描述

Summary概括

So to summarize, my question is how do I generate random coordinates given that they are at the edge of the plot/canvas.总而言之,我的问题是如何生成随机坐标,因为它们位于绘图/画布的边缘。 Any advice or help will be appreciated.任何建议或帮助将不胜感激。

One possible approach (despite not very elegant) is the following: divide horizontal and vertical points Suppose you want to draw a point at the top or at the bottom of the window.一种可能的方法(尽管不是很优雅)如下:划分水平点和垂直点假设您要在 window 的顶部或底部绘制一个点。 Then,然后,

  1. Select randomly the y coordinate as b or - b Select 随机将y坐标设为b或 - b
  2. Select randomly (uniform distribution) the x coordinate Select 随机(均匀分布) x坐标

Similar approach for right and left edges of the window. window 的左右边缘的类似方法。

Hope that helps.希望有帮助。

You could use this, but this is assuming you want to discard them when it is found they aren't on the edge.你可以使用它,但这是假设你想在发现它们不在边缘时丢弃它们。

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

And then do the same for y.然后对 y 做同样的事情。

Here's a way to do that:这是一种方法:

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

# This is the new code
reset_axis = np.random.choice([True, False], n) # select which axis to reset
reset_direction = np.random.choice([a,b], n) # select to go up / right or down / left

coordx[reset_axis] = reset_direction[reset_axis]
coordy[~reset_axis] = reset_direction[~reset_axis]
# end of new code. 

# 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()

The result is:结果是:

在此处输入图像描述

Here is what you can do:这是您可以执行的操作:

from random import choice
import matplotlib.pyplot as plt
from numpy.random import random_sample

n = 6
a = 5
b = -5

plt.xlim((b,a))
plt.ylim((b,a))

for i in range(n):
    r = (b - a) * random_sample() + a
    random_point = choice([(choice([a,b]), r),(r, choice([a,b]))])
    plt.scatter(random_point[0],random_point[1])

plt.show()

Output: Output:

在此处输入图像描述

Geometrically speaking, being on the edge requires that a point satisfy certain conditions.从几何上讲,处于边缘需要一个点满足某些条件。 Assuming that we are talking about a grid whose dimensions are defined by x ~ [0, a] and y ~ [0, b] :假设我们正在讨论一个网格,其尺寸由x ~ [0, a]y ~ [0, b]定义:

  • The y-coordinate is either 0 or b , with the x-coordinate within [0, a] , or y 坐标是 0 或b ,x 坐标在[0, a]内,或者
  • The x-coordinate is either 0 or a , with the y-coordinate within [0, b] x 坐标为 0 或a ,y 坐标在[0, b]范围内

There are obviously more than one way to go about this, but here is a simple method to get you started.显然,go 的方法不止一种,但这里有一个简单的方法可以帮助您入门。

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()

Can you try this out?你能试试这个吗?

import numpy as np
import matplotlib.pyplot as plt

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

import random

coordx,coordy=[],[]
for i in range(n):
    xy = random.choice(['x','y'])
    if xy=='x':
        coordx.append(random.choice([b,a])) # generate random x
        coordy.append(random.random()) # generate random y
    if xy=='y':
        coordx.append(random.random()) # generate random x
        coordy.append(random.choice([b,a])) # generate random y

# 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()

Here is a sample output:这是一个示例 output: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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