Skip to content

Instantly share code, notes, and snippets.

@yock
Created March 14, 2017 02:47
Show Gist options
  • Select an option

  • Save yock/d0cd4912f29cd8a4fad94dc7788a61c8 to your computer and use it in GitHub Desktop.

Select an option

Save yock/d0cd4912f29cd8a4fad94dc7788a61c8 to your computer and use it in GitHub Desktop.
Pi Day!
const iterations = 1000000;
const max = 1000000;
let count = 0;
const random = () => {
return Math.floor(Math.random() * max);
}
const euclid_gcd = (a, b) => {
if (b) {
return euclid_gcd(b, a % b);
} else {
return Math.abs(a);
}
}
for (let i = 0; i < iterations; i++) {
const gcd = euclid_gcd(random(), random());
if (gcd === 1) {
count++;
}
}
console.log(Math.sqrt(6 / (count / iterations)));
ITERATIONS = 1000000
MAX = 1000000
prng = Random.new
count = 0
ITERATIONS.times do
gcd = prng.rand(MAX).gcd(prng.rand(MAX))
count += 1 if gcd == 1
end
puts Math.sqrt(6.0 / (count.to_f / ITERATIONS.to_f))
@yock

yock commented Mar 14, 2017

Copy link
Copy Markdown
Author

Estimating the value of Pi by sampling the greatest common denominator between two large random numbers. First sample a large number of large integer pairs, taking note of each pair that does not share a common denominator greater than 1. Next, find the ratio of this count to the number of samples taken. The relationship between this ratio and pi is the square root of the quotient of 6 divided by that ratio.

sqrt(6 / (count / samples))

Inspired by Matt Parker's ridiculous dice-based sampling video for this year's Pi Day.
https://www.youtube.com/watch?v=RZBhSi_PwHU

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment