Jac*_*246 11 python distribution point
我想知道如何生成出现在循环分布中的随机数.
我能够在矩形分布中生成随机点,使得点在(0 <= x <1000,0 <= y <1000)的平方内生成:
我将如何继续在一个圆圈内生成点,以便:
(x-500)^ 2 +(y-500)^ 2 <250000?
f43*_*d65 10
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))
Run Code Online (Sandbox Code Playgroud)
在你的例子中circle_x是500原样circle_y.circle_r是500.
基于这个答案,计算半径的另一个版本可以获得均匀分布的点
u = random.random() + random.random()
r = circle_r * (2 - u if u > 1 else u)
Run Code Online (Sandbox Code Playgroud)
第一个答案:一个简单的解决方案是在继续之前检查结果是否满足您的等式.
生成x,y(有多种方法可以随机化到选择范围内)
检查((x-500)^ 2 +(y-500)^ 2 <250000)是否为真,如果不是,则重新生成.
唯一的缺点是效率低下.
第二回答:
或者,你可以做一些类似于黎曼和类似于近似积分的东西.通过将圆圈分成许多矩形来近似圆圈.(矩形越多,越准确),并对圆内的每个矩形使用矩形算法.
你需要的是从(极性形式)采样:
r, theta = [math.sqrt(random.randint(0,500))*math.sqrt(500), 2*math.pi*random.random()]
Run Code Online (Sandbox Code Playgroud)
然后r,您可以转换并theta返回笛卡尔坐标x并y通过
x = 500 + r * math.cos(theta)
y = 500 + r * math.sin(theta)
Run Code Online (Sandbox Code Playgroud)
相关(虽然不是 Python),但给出了想法。
| 归档时间: |
|
| 查看次数: |
13330 次 |
| 最近记录: |