首页 > 解决方案 > 圆内到处都是随机点

问题描述

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

// 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。我怎样才能做到这一点?

标签: javascriptmathrandompolar-coordinates

解决方案


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

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

推荐阅读