Javascript 圆内的任意点

Javascript 圆内的任意点,javascript,math,random,polar-coordinates,Javascript,Math,Random,Polar Coordinates,我使用下面的代码随机生成一些位于圆内的x,y: // r is distance from the center and a is angle // R is radius of circle // M is center r = R * Math.random(); a = 2 * Math.PI * Math.random(); x = Math.round(r * Math.cos(a) + M); y = Math.round(r * Math.sin(a) + M); 问题是,当

我使用下面的代码随机生成一些位于圆内的x,y:

// r is distance from the center and a is angle
// R is radius of circle
// M is center

r = R * Math.random();
a = 2 * Math.PI * Math.random();

x = Math.round(r * Math.cos(a) + M);
y = Math.round(r * Math.sin(a) + M);
问题是,当越来越靠近圆心时,在该位置获得x,y的机会越来越大


但我要找的是,在圆中有完全随机的x,y。我怎样才能做到这一点呢?

由于雅可比,你必须取平方根

r = R *  Math.sqrt(Math.random());

你可以在边R的正方形上随机生成x,y,然后检查它们是否位于圆内

x = 2 * R * Math.random()
y = 2 * R * Math.random()
r = Math.sqrt((x - M)*(x - M) + (y - M) * (y - M))
if(r < R) {
    // show x,y
}
x=2*R*Math.random()
y=2*R*Math.random()
r=数学sqrt((x-M)*(x-M)+(y-M)*(y-M))
if(r
要在圆内均匀分布点,只需在边长等于2R的正方形中随机选取点,然后丢弃掉圆外的任何点

x = 2 * R * Math.random()
y = 2 * R * Math.random()
r = Math.sqrt((x - M)*(x - M) + (y - M) * (y - M))
if(r < R) {
    // show x,y
}
这可以在没有任何三角运算或超越运算的情况下完成:

let x, y;
do {
    x = 2 * Math.random() - 1.0;  // range [-1, +1)
    y = 2 * Math.random() - 1.0;
} while ((x * x + y * y) >= 1);   // check unit circle

// scale and translate the points
x = x * R + Mx;
y = y * R + My;

在循环的每个过程中,大约21.5%的分数将被丢弃,但这仍然比使用
sin
cos

几乎正确的答案更快-但是与没有昂贵的
sqrt()
操作的R^2相比。也可以使用例如
x=R*(Math.random()-0.5)
你是对的,这比较便宜-我只是想解释一下我认为你在(缺少)负坐标方面有问题。这不是一个计算效率高的算法拒绝采样可能会更快。关于这个问题的有趣讨论:(维基百科)