题目
Given the radius and x-y positions of the center of a circle, write a function randPoint which generates a uniform random point in the circle.
Note:
- input and output values are in floating-point.
- radius and x-y position of the center of the circle is passed into the class constructor.
- a point on the circumference of the circle is considered to be in the circle.
- randPoint returns a size 2 array containing x-position and y-position of the random point, in that order.
解题思路
拒绝采样,随机-1到1直接的一个点,如果在单位元范围内,进行缩放和平移对应到要求的点,不在则继续随机
代码
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.r = radius
self.x = x_center
self.y = y_center
def randPoint(self) -> List[float]:
while True:
u = 2 * random.random() - 1
v = 2 * random.random() - 1
if u * u + v * v <= 1:
return [self.x + u * self.r, self.y + v * self.r]