【发布时间】:2017-06-14 05:01:15
【问题描述】:
我正在尝试在一个环内生成随机 x 和 y 坐标,该环的外半径为 3.5,内半径为 2。因此,x 和 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 的正方形。我似乎找不到问题所在。我也不确定这是一个编码错误,还是一些愚蠢的数学问题。既然你们通常两者都擅长,你能看出我在这里做错了什么吗?
【问题讨论】:
-
为什么不生成一个随机的角度和距离,然后将其转换为 x、y 对?
-
@MartijnPieters 如果您均匀生成距离,则内环中的点会更密集。
标签: python python-2.7 numpy math