Skip to content

Instantly share code, notes, and snippets.

@alexcorvi
Last active March 14, 2017 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexcorvi/9ea014614e733af515d2a1e585bcd5e8 to your computer and use it in GitHub Desktop.
Save alexcorvi/9ea014614e733af515d2a1e585bcd5e8 to your computer and use it in GitHub Desktop.
Calculate Pi Value from random numbers
function getPi(){
function getRand(maxRand){
return Math.floor(Math.random()*maxRand);
}
function gcd(a,b) {
if (!b) return a;
else return gcd(b,a%b);
};
let coPrimes = 0;
const iterations = 10000000;
const maxRand = 10000000;
for (var i = 0; i < iterations; i++) {
const n1 = getRand(maxRand);
const n2 = getRand(maxRand);
if(gcd(n1,n2) === 1) coPrimes++;
}
const proportion = coPrimes/iterations;
const result = Math.sqrt(6/proportion);
console.log(result);
return result;
}
// details: https://www.youtube.com/watch?v=RZBhSi_PwHU
function getPi() {
function getRandAxis(){
return (Math.random()*2) - 1;
}
function isInside(a,b){
if((a*a) + (b*b) <= 1) return true;
else return false;
}
let inside = 0;
const iterations = 10000000;
for (var i = 0; i < iterations; i++) {
if(isInside(getRandAxis(),getRandAxis())) inside++;
}
const result = 4*(inside/iterations);
console.log(result);
return result;
}
// details: https://www.youtube.com/watch?v=VJTFfIqO4TU
// code ported from c++ https://repl.it/GTlL/0
// credits for the c++ code goes to https://github.com/antwankakki
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment