Skip to content

Instantly share code, notes, and snippets.

@PhDP
Created August 2, 2013 17:37
Show Gist options
  • Save PhDP/6141763 to your computer and use it in GitHub Desktop.
Save PhDP/6141763 to your computer and use it in GitHub Desktop.
"Monte Carlo" example (Introductory C++)
/*
phdp@dell-xps:~$ vim main.cc
phdp@dell-xps:~$ clang++ -std=c++11 main.cc -o main
phdp@dell-xps:~$ time ./main
The seed is 1375464851
3.14157
real 0m27.375s
user 0m27.308s
sys 0m0.004s
phdp@dell-xps:~$ clang++ -O3 -std=c++11 main.cc -o main
phdp@dell-xps:~$ time ./main
The seed is 1375464890
3.14165
real 0m1.769s
user 0m1.764s
sys 0m0.000s
*/
#include <iostream>
#include <random>
#include <ctime>
using namespace std;
int main() {
const unsigned int seed = time(0);
cout << "The seed is " << seed << endl;
mt19937_64 rng(seed);
uniform_real_distribution<double> unif;
const unsigned int iterations = 100000000;
unsigned int inside = 0;
for (int i = 0; i < iterations; i++) {
const double x = unif(rng);
const double y = unif(rng);
if (x * x + y * y < 1.0) {
inside++;
}
}
cout << 4.0 * ((double)inside / iterations) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment