Create random number within an annulus

前端 未结 2 795
长发绾君心
长发绾君心 2020-12-29 14:05

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, max         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 14:32

    The method you're using should work pretty efficiently for a thick annulus (where r1 <<< r2). If you're dealing instead with a narrow annulus (r2 - r1 <<< r1), then you may want to use something like this instead:

    r = random.uniform(r1, r2)
    theta = random.uniform(0, 2 * PI)
    x = r * math.sin(theta)
    y = r * math.cos(theta)
    

    Note that this gives mildly non-uniform results (there's a constant distribution of points per unit angle, not per unit area).

提交回复
热议问题