python随机生成一个地区地址_试图在python的环中生成随机的x,y坐标

1586010002-jmsa.png

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

I wrote the following function:

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

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

sPU0E.gif

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值