Generate Random Point in a Circle

To create random points inside a circle, you can generate random polar coordinates (radius and angle) and then convert them to Cartesian coordinates. Here’s how you can implement the class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import random
import math

class Solution:

    def __init__(self, radius: float, x_center: float, y_center: float):
        self.radius = radius
        self.x_center = x_center
        self.y_center = y_center

    def randPoint(self) -> List[float]:
        r = self.radius * math.sqrt(random.random()) # Square root ensures uniform distribution
        theta = random.uniform(0, 2 * math.pi) # Random angle in radians
        x = r * math.cos(theta) + self.x_center
        y = r * math.sin(theta) + self.y_center
        return [x, y]

Explanation:

  • In the randPoint method, we first generate a random radius r that is within the circle’s radius. We take the square root of the random value to ensure uniform distribution within the circle.
  • Next, we generate a random angle theta in radians, ranging from (0) to (2\pi).
  • Using the generated r and theta, we convert from polar to Cartesian coordinates and return the point.

This code snippet will generate random points inside the given circle with uniform distribution, and it meets the constraints mentioned in the problem.