在圆环内创建随机数 [英] Create random number within an annulus

查看:175
本文介绍了在圆环内创建随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying generate a random number that is within an annulus, i.e. we have a max and min radius. I tried doing:

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或有另一种方法?

But this is very slow. Is it possible to feed more contraints into random.uniform or is there another method?

推荐答案

通常,您可以直接绘制正确的分布或使用拒绝.

In general you can either draw the correct distribution directly or use rejection.

  • 在[0,2pi)上均匀绘制theta:theta = random.uniform(0,2*pi)
  • 幂律分布r ^ 1 中提取r.

  • draw theta uniformly on [0,2pi): theta = random.uniform(0,2*pi)
  • draw r from the power-law distribution r^1.

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

The only complexity compared to doing this for a circle is that you PDF runs from [r_min,r_max] not [0,r_max]. This leads to

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

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)

,您可以稍微简化一下.

and you can simplify slightly.

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

then compute (x,y) by the usual transformation from radial coordinates
x = r * cos(theta)
y = r * sin(theta)

这种集成PDF,对CDF进行归一化和求逆的方法是通用的,有时被称为采样基本定理".

This method of integrating the PDF, normalizing the CDF and inverting is general and is sometimes called the "Fundamental Theorem of Sampling".

在一个足以容纳环面的盒子上绘制(x,y),然后拒绝所有`r = sqrt(x x + y y)超过r_max或小于r_min的情况.

Draw (x,y) on a box big enough to contain the annulus, then reject all cases where `r = sqrt(xx + yy) exceeds r_max or is less than r_min.

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

This is reasonably efficient if the hole in the middle is small, and very inefficient if the hole is large.

这篇关于在圆环内创建随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆