试图在python的圆环内生成随机的x,y坐标 [英] Trying to generate random x,y coordinates within a ring in python

查看:662
本文介绍了试图在python的圆环内生成随机的x,y坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一个圆环中生成随机的x和y坐标,该圆环的外半径为3.5,内半径为2.因此,x和y必须满足以下条件:

I am trying to generate random x and y coordinates within a ring, which has an outer radius of 3.5 and an inner radius of 2. Therefor the following must be true for x and y:

x**2 + y**2 < 12.25 and x**2 + y**2 > 4

我编写了以下函数:

def meteorites():
    circle = False
    while circle == False:        
        r = np.array([uniform(-6., 6.), uniform(-6., 6.)])
        # we will regenerate random numbers untill the coordinates
        # are within the ring x^2+y^2 < 3,5^2 and x^2+y^2 > 2^2
        if (r[0]**2+r[1]**2 < 12.25) and (r[0]**2+r[1]**2 > 4.):
            circle = True

       else :
            circle = False

    return r[0], r[1]

x = np.zeros(1000)
y = np.zeros(1000)
for i in range(1000):
    x[i] = meteorites()[0]
    y[i] = meteorites()[1]
plt.scatter(x,y)
plt.show()  

当我绘制结果坐标时,我得到一个从-3.5到3.5的平方.我似乎找不到问题.我也不确定这是编码错误还是某些模拟数学问题.既然你们俩通常都擅长,您能在这里看到我做错了吗?

When I plot the resulting coordinates I get a square from -3.5 to 3.5. I can't seem to find the problem. I'm also not sure if it's a coding error, or some dum math problem. Since you guys are usually good at both, can you see what I'm doing wrong here?

推荐答案

要获得环中随机点的均匀分布,应考虑细圆形区域的相对面积. 它如何作用于圈子

To get uniform distribution of random point in the ring, one should take relative areas of thin circular regions into account. How it works for the circle

对于您的情况,在内外半径的平方范围内生成SquaredR的均匀分布.伪代码:

For your case generate uniform distribution of SquaredR in range of squared inner and outer radii. Pseudocode:

 Fi  = RandomUniform(0, 2 * Pi)
 SquaredR  = RandomUniform(inner*inner, outer*outer)
 R = Sqrt(SquaredR)
 x,y = R * Cos(Fi), R * Sin(Fi)

这篇关于试图在python的圆环内生成随机的x,y坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆