我想知道如何生成呈圆形分布的随机数。
我能够生成在矩形分布内的随机点,这些点生成在 (0 <= x < 1000, 0 <= y < 1000) 的正方形内:
那么,我该如何生成在圆形分布内的点,使得:
(x−500)^2 + (y−500)^2 < 250000?
我想知道如何生成呈圆形分布的随机数。
我能够生成在矩形分布内的随机点,这些点生成在 (0 <= x < 1000, 0 <= y < 1000) 的正方形内:
那么,我该如何生成在圆形分布内的点,使得:
(x−500)^2 + (y−500)^2 < 250000?
import random
import math
# radius of the circle
circle_r = 10
# center of the circle (x, y)
circle_x = 5
circle_y = 7
# random angle
alpha = 2 * math.pi * random.random()
# random radius
r = circle_r * math.sqrt(random.random())
# calculating coordinates
x = r * math.cos(alpha) + circle_x
y = r * math.sin(alpha) + circle_y
print("Random point", (x, y))
在你的例子中,circle_x
为500,如同 circle_y
的取值也是500。而 circle_r
则为500。
另一种计算半径以获得均匀分布点的方法是基于这个答案的。
u = random.random() + random.random()
r = circle_r * (2 - u if u > 1 else u)
r
的 random.random()
部分取平方根,这样它将成为均匀分布。 - Ulf Aslakrandom
函数。 - Veedracr, theta = [math.sqrt(random.randint(0,500))*math.sqrt(500), 2*math.pi*random.random()]
r
和 theta
转换为直角坐标 x
和 y
:x = 500 + r * math.cos(theta)
y = 500 + r * math.sin(theta)
相关链接(虽然不是Python),但可以提供思路。
here's an example hope could help someone :).
randProba = lambda a: a/sum(a)
npoints = 5000 # points to chose from
r = 1 # radius of the circle
plt.figure(figsize=(5,5))
t = np.linspace(0, 2*np.pi, npoints, endpoint=False)
x = r * np.cos(t)
y = r * np.sin(t)
plt.scatter(x, y, c='0.8')
n = 2 # number of points to chose
t = np.linspace(0, 2*np.pi, npoints, endpoint=False)[np.random.choice(range(npoints), n, replace=False, p=randProba(np.random.random(npoints)))]
x = r * np.cos(t)
y = r * np.sin(t)
plt.scatter(x, y)
import random
import math
circle_x = 500
circle_y = 500
a = random.randint(0,500) * 2 * math.pi
r = 1 * math.sqrt(random.randint(0,500))
x = r * math.cos(a) + circle_x
y = r * math.sin(a) + circle_y
我会使用极坐标:
r_squared,theta = [random.randint(0,250000),2*math.pi*random.random()]
然后r始终小于或等于半径,theta始终在0到2*pi弧度之间。
由于r不在原点上,因此如果我理解正确,您将始终将其转换为以500, 500为中心的向量
x = 500 + math.sqrt(r_squared)*math.cos(theta)
y = 500 + math.sqrt(r_squared)*math.sin(theta)
由于 this 的缘故,选择r_squared随机。
x = 500 + r*math.cos(theta)
y = 500 + r*math.sin(theta)
是这样的吗? - fiacrer_squared, theta = [random.randint(0,250000), 2*math.pi*random.random()]
然后应用变换
x = 500 + math.sqrt(r_squared)*math.cos(theta)
y = 500 + math.sqrt(r_squared)*math.sin(theta)
- fiacre