Solution
To generate a random point within a circle of radius \( R \), you can use polar coordinates. The idea is:
-
Generate a random angle \( \theta \) between \( [0, 2 \pi] \)
-
Generate a random radius r, ensuring uniform distribution within the circle by using
\( r = R\sqrt u \) where \( u\) is a random number between 0 and 1.
-
Convert to Cartesian coordinates using :
\( x = r*cos(\theta)\)
\( y = r*sin(\theta)\)
import random
import math
class Solution:
def sample_point_in_circle(self, R:int):
"""Sample (x, y) points."""
theta = random.uniform(0, 2 * math.pi) # Random angle
r = R * math.sqrt(random.uniform(0, 1)) # Random radius
x = r * math.cos(theta)
y = r * math.sin(theta)
return (x, y)
Why use \( r = R . \sqrt u \) instead of \( r = R.u \) ?
If we use \( r= R.u \), the points will be denser near the center instead of being uniformly distributed. Using
\( r = R . \sqrt(u) \) ensures equal probability across the entire area of the circle.
There is detailed explnation can be found in this articles