gpt4 book ai didi

python - 在环内创建随机数

转载 作者:太空狗 更新时间:2023-10-29 20:42:48 25 4
gpt4 key购买 nike

我正在尝试生成一个位于环形内的随机数,即我们有最大和最小半径。我尝试这样做:

while True:
x=random.uniform(-maxR, maxR)
y=random.uniform(-maxR, maxR)
R=math.sqrt(x**2 + y**2)
if R <= maxRadius and R >= minRadius:
if x>= -maxRadius and x <= maxRadius and x<=-minRadius and x>= minRadius:
print "passed x"
if y>= -maxRadius and y <= maxRadius and y<=-minRadius and y>= minRadius:
break

但这很慢。是否可以向 random.uniform 提供更多约束,或者是否有其他方法?

最佳答案

一般情况下,您可以直接绘制正确的分布或使用拒绝。

直接绘制使用

  • 在 [0,2pi] 上均匀绘制 theta:theta = random.uniform(0,2*pi)
  • the power-law distribution r^1 中绘制 r .

    与对圆进行此操作相比,唯一的复杂性是您的 PDF 从 [r_min,r_max] 而不是 [0,r_max] 运行。这导致

    CDF = A\int_{r_min}^{r} r' dr' = A (r^2 - r_min^2)/2

    A 的归一化常数

    A = 2/(r_max*r_max - r_min*r_min)

    暗示

    r = sqrt(2*random.uniform(0,1)/A + r_min*r_min)

    你可以稍微简化一下。

  • 然后通过通常的径向坐标变换计算 (x,y)
    x = r * cos(θ)
    y = r * sin(theta)

这种对 PDF 进行积分、CDF 归一化和反演的方法是通用的,有时也称为“采样基本定理”。

拒绝

在一个大到足以包含圆环的盒子上绘制 (x,y),然后拒绝所有 r = sqrt(xx + yy) 超过 r_max 或小于 r_min 的情况。

如果中间的孔很小,这是相当有效的,如果孔很大,则效率很低。

关于python - 在环内创建随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9048095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com