Last active
March 26, 2017 01:10
-
-
Save railken/4d9ea7518caf1d8c675ee09149210ed3 to your computer and use it in GitHub Desktop.
Generating PI using random numbers
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
| <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