jeudi 2 mars 2017

Node.js Math.random() not working

I wrote this piece of code to estimate Pi using Monte Carlo simulation, but I noticed that the results are always around 2.0 no matter the amount of iterations. I think it's probably that Math.random() is not working. The code is run un Mac OS Sierra using Node v7.5.0.

Any ideas?

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




Aucun commentaire:

Enregistrer un commentaire