该算法的工作原理:它首先生成一个点的随机坐标。然后它找到每个点到圆中心的距离。如果距离<=1,则该点在圆内,否则在圆外。圆内点数与总点数之比接近pi。
我想让这个算法运行得更快。我该怎么做?
function calc(iterations) {
pointCircle = 0, total = 0, x = 0, y = 0, distance = 0, pi = 0;
for (let i = 0; i < iterations; i++) {
x = Math.random().toFixed(1);
y = Math.random().toFixed(1);
distance = Math.sqrt(x * x + y * y);
if (distance <= 1) {pointCircle++;}total++;
}
pi = 4 * (pointCircle / total); console.log(pi);
}
Run Code Online (Sandbox Code Playgroud)