Node.js Math.random()不起作用

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

有任何想法吗?

// 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 不是幂指数,它是按位XOR 。

要求幂,请使用x*xMath.pow(x,2)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"); 
Interesting Posts