Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

圆内随机生成点 #3

Open
ZhangCheng-zh opened this issue Jun 5, 2022 · 0 comments
Open

圆内随机生成点 #3

ZhangCheng-zh opened this issue Jun 5, 2022 · 0 comments

Comments

@ZhangCheng-zh
Copy link
Owner

ZhangCheng-zh commented Jun 5, 2022

拒绝采样

也就是在一个更大的范围内生成随机点,并拒绝掉那些不在题目给定范围内的随机数。

取恰好覆盖圆的正方形为采样范围:

⚠️注意
在正方形中生成点时(正方形中心的坐标简记为原点),如果我们在 [-R, R)[−R,R) 的范围内生成随机数,那么是无法生成到横坐标或纵坐标恰好为 RR 的点,对应到圆上时,会有圆周上与正方形边相切的两个点无法随机到。我们可以在生成时稍微提高右边界(例如 2R + ϵ,其中 ϵ 是一个很小的常数,例如 10^{-7},或者直接忽略这两个点,因为它们的勒贝格测度为零。

class Solution {
    constructor(radius: number, x_center: number, y_center: number) {
        this.xc = x_center
        this.yc = y_center
        this.r = radius
    }
    xc: number
    yc: number
    r: number

    randPoint(): number[] {
        let ans = null 
        while (!ans) {
            const x = Math.random() * 2 * this.r - this.r
            const y = Math.random() * 2 * this.r - this.r
            if (Math.pow(x, 2) + Math.pow(y, 2) <= Math.pow(this.r, 2)) ans = [this.xc + x, this.yc + y]
        }
        return ans
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant