Created
March 14, 2017 06:38
-
-
Save limzykenneth/90cdca446d8e167fd12e7bac0043d3d4 to your computer and use it in GitHub Desktop.
π day 2017 (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
#include <iostream> | |
#include <math.h> | |
#include <stdint.h> | |
#include <random> | |
#include <chrono> | |
#include <stdlib.h> | |
using namespace std; | |
uint64_t gcd(uint64_t a, uint64_t b); | |
int main(int argc, char* argv[]){ | |
if(argc > 2){ | |
cerr<<"\n\tJust one option specifying number of iterations please. Leave blank for default (50,000,000).\n"<<endl; | |
return 1; | |
} | |
uint64_t iterations = 50000000; | |
if(argv[1]){ | |
iterations = strtoul(argv[1], NULL, 0); | |
} | |
cout<<"Calculating PI..."<<endl; | |
unsigned seed1 = chrono::system_clock::now().time_since_epoch().count(); | |
mt19937_64 g1 (seed1); | |
uint64_t i = 1; | |
uint64_t count = 0; | |
while(i < iterations){ | |
uint64_t n1 = g1(); | |
uint64_t n2 = g1(); | |
if(gcd(n1, n2) == 1){ | |
count++; | |
} | |
i++; | |
} | |
long double probability = (long double)count/(long double)iterations; | |
long double pi = sqrt(6/probability); | |
cout<<pi<<endl; | |
return 0; | |
} | |
uint64_t gcd(uint64_t a, uint64_t b) { | |
return b == 0 ? a : gcd(b, a % b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment