圆圈内的随机点
Random points all over inside of a circle
我正在使用下面的代码随机生成一些位于圆圈内的 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
}
要在圆内均匀分布点,只需在边长等于 2R 的正方形中随机选取点,然后丢弃落在圆外的任何点。
这可以在没有任何三角或超越运算的情况下完成:
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
.
更快结束
我正在使用下面的代码随机生成一些位于圆圈内的 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
}
要在圆内均匀分布点,只需在边长等于 2R 的正方形中随机选取点,然后丢弃落在圆外的任何点。
这可以在没有任何三角或超越运算的情况下完成:
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
.