2
我寫了這段代碼來使用Monte Carlo模擬來估計Pi,但我注意到無論迭代的數量如何,結果總是在2.0左右。我想這可能是Math.random()不起作用。 代碼使用Node v7.5.0在Mac OS Sierra上運行。Node.js Math.random()不起作用
任何想法?
// Begin of code
iterations = 100000000;
in_circle = 0;
function find_pi(){
for (i = 0; i < iterations; i++){
x = 1 - 2 * Math.random();
y = 1 - 2 * Math.random();
if ((x^2 + y^2) < 1)
in_circle++;
}
console.log("in_circle = ", in_circle);
console.log("iterations = ", iterations);
console.log("Estimated PI Value = ", 4 * in_circle/iterations);
}
var startTime = Date.now();
find_pi();
var endTime = Date.now();
console.log("\n===== Took us: " + (endTime - startTime) + " milliseconds");
好極了!謝謝! –