Last active
March 14, 2017 02:45
-
-
Save alexcorvi/9ea014614e733af515d2a1e585bcd5e8 to your computer and use it in GitHub Desktop.
Calculate Pi Value from random numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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