Generate Random Point In A Circle Problem
Description
LeetCode Problem 478.
Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle.
Implement the Solution class:
- Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center).
- randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y].
Example 1:
Input
["Solution", "randPoint", "randPoint", "randPoint"]
[[1.0, 0.0, 0.0], [], [], []]
Output
[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]
Explanation
Solution solution = new Solution(1.0, 0.0, 0.0);
solution.randPoint(); // return [-0.02493, -0.38077]
solution.randPoint(); // return [0.82314, 0.38945]
solution.randPoint(); // return [0.36572, 0.17248]
Constraints:
- 0 < radius <= 10^8
- -10^7 <= x_center, y_center <= 10^7
- At most 3 * 10^4 calls will be made to randPoint.
Solution
Approach: Polar Coordinates with a Square-Root Radius
Pick a random direction and a random distance from the center, then convert to x and y:
angleis uniform in[0, 2π).distance = radius * sqrt(u), whereuis uniform in[0, 1).- Return
[x_center + distance * cos(angle), y_center + distance * sin(angle)].
The square root is the part people get wrong. If distance were simply radius * u, half of the points would land within radius / 2 of the center, but that inner disk has only a quarter of the area, so the points would crowd the middle.
For a uniform point, the chance of landing within distance d of the center must equal the share of the area inside that distance: (d / radius)2. Setting d = radius * sqrt(u) gives (d / radius)2 = u, and u is uniform, so every disk around the center gets exactly its share. For example, half the points land within radius / sqrt(2), and that inner disk is exactly half of the area.
A second valid approach is rejection sampling: pick a point uniformly in the bounding square and retry until it falls inside the circle (about 1.27 tries on average). The polar method needs no loop.
Complexity: O(1) time and O(1) space per call.
import math
import random
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]:
# sqrt makes the distance follow the area: half the points land within radius / sqrt(2).
distance = self.radius * math.sqrt(random.random())
angle = 2 * math.pi * random.random()
return [self.x_center + distance * math.cos(angle),
self.y_center + distance * math.sin(angle)]