Created
March 14, 2017 02:47
-
-
Save yock/d0cd4912f29cd8a4fad94dc7788a61c8 to your computer and use it in GitHub Desktop.
Pi Day!
This file contains hidden or 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
| 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))); |
This file contains hidden or 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
| 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)) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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