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

Upvotes: 3

Views: 896

Answers (1)

Freyja
Freyja

Reputation: 40824

x^2 is not exponentiation, it's bitwise XOR.

To do exponentiation, use x*x, Math.pow(x,2) or x**2. If you do this, you will correctly estimate π≈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");

Upvotes: 1

Related Questions