Random Point in a Circle
Suppose you’re given the centre of the circle C (xc,yc). You are also given its radius R. How do you return a random point in a circle (each point in the circle should have the same probability of being returned)?
Tools/Functions Provided
Assume that a function f is provided which returns a random value between 0 and 1.
Approach
It is difficult to think in terms of cartesian coordinates, because the range of x is dependent on y and vice versa. So we think in terms of polar coordinates.
First, we choose a random distance r from the centre C. That is returned by f*R.
Now, we choose a random angle θ. This is returned by f*2π.
So, the random point (x,y) is given by (xc+r*cos(θ), yc+r*sin(θ)).
Problems?
The above approach seems good to go. However, does there seem to be a problem with it?
Suppose that distance r can take only two values, R/3 and 2*R/3. So what is the probability that the point is selected from the outer circle (with radius 2*R/3) ? It’s exactly 1/2, because distance is randomly chosen from the two values with equal probability. But this doesn’t seem right, does it?
If the outer circle has twice the radius, it also has twice the circumference. So, probability of selecting a point from the outer circle(r = 2*R/3) should be double than that of selecting a point from the inner circle(r = R/3).
This shows that the probability distribution function should not be constant with distance, but should be directly proportional to distance.
The New PDF
So, our new probability density function is proportional to distance. Let’s call this probability density function p(r). Then we have:
p(r) = k*r
∫k*r*dr = 1
k = 2/R²
So, our pdf becomes 2*r/R², where r is the radial distance of the point. Our cumulative distribution function now becomes ∫p(r)*dr = r²/R².
Using sqrt(f)*r gives a point at distance x with probability 2*x/R². The proof of this will be covered in the next blog.
Thus, the final desired generation would be:
θ = 2*π*f
r = sqrt(f)*R
x = xc + r*cos(θ)
y = yc + r*sin(θ)
Next article coming soon.