【问题标题】:Random points all over inside of a circle圆内到处都是随机点
【发布时间】:2018-08-07 12:50:24
【问题描述】:

我正在使用以下代码随机生成一些位于圆圈内的 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。我怎样才能做到这一点?

【问题讨论】:

标签: javascript math random polar-coordinates


【解决方案1】:

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

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

【讨论】:

  • 这不是一个计算效率高的算法
  • 拒绝采样可能会更快。
【解决方案2】:

要在圆内均匀分布点,只需在边长等于 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% 的点将被丢弃,但这仍然应该比使用 sincos 更快。

【讨论】:

    【解决方案3】:

    您可以在边 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
    }
    

    【讨论】:

    • 几乎是正确的答案 - 但与没有昂贵的 sqrt() 操作的 R^2 相比。也使用例如x = R * (Math.random() - 0.5)
    • 你说得对,那更便宜——我只是想理解这个想法
    • 我认为您有(缺少)负坐标的问题。
    猜你喜欢
    • 2019-01-17
    • 2012-02-21
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多