Back to questions

How do you uniformly sample points at random from a circle with radius R?

This is the same question as problem #39 in the Statistics Chapter of Ace the Data Science Interview!

This can be proved using the inverse-transform method, whereby we sample from a uniform distribution and then simulate the points on the circle employing the inverse cumulative distribution functions (i.e., inverse CDFs).

We can define a random point within the circle using a given radius value and an angle (and obtain the corresponding *x*, *y* values from polar coordinates). To sample a random radius, consider the following.

If we sample points from a radius *r*, we know that there are 2πr points to consider (i.e., the circumference of the circle). Likewise, if we sample a radius 2*r*, there are 4π*r* points to consider. Therefore, we have the following probability density function given by the following:

$f_R(r) = \frac{2r}{R^2}$

This follows from the CDF, which is given by the ratio of the areas of the two circles:

$F_R(r) = \frac{r^2}{R^2}$

Therefore, for the inverse sampling, we want the following:

$y = \frac{r^2}{R^2}$

which simplifies to the following:

$\sqrt{R^2y} = r$

Therefore, we can sample

$Y \sim U(0,1)$

and the corresponding radius will be the following:

$r = R\sqrt{y}$

For the corresponding angles, we can sample theta uniformly from the range 0 to 2π:

$\theta \in [0, 2\pi]$

and then set the following:

$x = r\cos(\theta), y = r\sin(\theta)$