Skip to content

Instantly share code, notes, and snippets.

@railken
Last active March 26, 2017 01:10
Show Gist options
  • Select an option

  • Save railken/4d9ea7518caf1d8c675ee09149210ed3 to your computer and use it in GitHub Desktop.

Select an option

Save railken/4d9ea7518caf1d8c675ee09149210ed3 to your computer and use it in GitHub Desktop.
Generating PI using random numbers
<script>
// Generating PI using random numbers
// Source: https://www.youtube.com/watch?v=RZBhSi_PwHU
var RAND_MIN = 1;
var RAND_MAX = 999999;
var NUMBERS = 999999;
var gcd = function(a, b)
{
if ( ! b) {
return a;
}
return gcd(b, a % b);
};
var rand = function(min, max)
{
return parseInt(Math.random() * (max - min) + min);
};
var total = 0;
var coprime = 0;
for (var i = 0; i < NUMBERS; i++) {
if (gcd(rand(RAND_MIN, RAND_MAX), rand(RAND_MIN, RAND_MAX)) == 1) {
coprime++;
}
total++;
}
var PI = Math.sqrt(6 / (coprime/total));
console.log("PI: ", PI);
document.write(PI)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment