Node.js Math.random() 不工作

Node.js Math.random() not working

我写了这段代码来使用 Monte Carlo 模拟来估计 Pi,但我注意到无论迭代次数如何,结果总是在 2.0 左右。我认为可能是 Math.random() 不起作用。 代码是 运行 un Mac OS Sierra 使用 Node v7.5.0.

有什么想法吗?

// 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");

x^2 不是 求幂,它是 bitwise XOR.

要求幂,请使用 x*xMath.pow(x,2) or x**2。如果这样做,您将正确估计 π≈3.14:

// Begin of code
iterations = 100000;
in_circle = 0;


function find_pi(){
    for ( i = 0; i < iterations; i++ ){
        x = 1 - 2 * Math.random();
        y = 1 - 2 * Math.random();

        if ( (x*x + y*y) < 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");