Generate a random point within a circle (uniformly)

前端 未结 21 2304
逝去的感伤
逝去的感伤 2020-11-22 15:45

I need to generate a uniformly random point within a circle of radius R.

I realize that by just picking a uniformly random angle in the interval [0 ... 2π),

21条回答
  •  隐瞒了意图╮
    2020-11-22 16:31

    First we generate a cdf[x] which is

    The probability that a point is less than distance x from the centre of the circle. Assume the circle has a radius of R.

    obviously if x is zero then cdf[0] = 0

    obviously if x is R then the cdf[R] = 1

    obviously if x = r then the cdf[r] = (Pi r^2)/(Pi R^2)

    This is because each "small area" on the circle has the same probability of being picked, So the probability is proportionally to the area in question. And the area given a distance x from the centre of the circle is Pi r^2

    so cdf[x] = x^2/R^2 because the Pi cancel each other out

    we have cdf[x]=x^2/R^2 where x goes from 0 to R

    So we solve for x

    R^2 cdf[x] = x^2
    
    x = R Sqrt[ cdf[x] ]
    

    We can now replace cdf with a random number from 0 to 1

    x = R Sqrt[ RandomReal[{0,1}] ]
    

    Finally

    r = R Sqrt[  RandomReal[{0,1}] ];
    theta = 360 deg * RandomReal[{0,1}];
    {r,theta}
    

    we get the polar coordinates {0.601168 R, 311.915 deg}

提交回复
热议问题