Created
April 12, 2014 15:44
-
-
Save kdungs/10542167 to your computer and use it in GitHub Desktop.
MC approximation of π.
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 <algorithm> | |
#include <iostream> | |
#include <random> | |
#include <utility> | |
#include <vector> | |
typedef float Number; | |
typedef std::pair<Number, Number> Point; | |
typedef std::mt19937 RandomGenerator; | |
Number ApproximatePi(const size_t N, RandomGenerator &rng) { | |
std::uniform_real_distribution<Number> dist(0.0, 1.0); | |
std::vector<Point> v(N); | |
std::generate(std::begin(v), std::end(v), [&]() { | |
return Point{dist(rng), dist(rng)}; | |
}); | |
size_t n_inside = std::count_if(std::begin(v), std::end(v), | |
[](const Point &p) { return p.first * p.first + p.second * p.second <= 1; } | |
); | |
return 4.0 * n_inside / N; | |
} | |
int main(int argc, char *argv[]) { | |
std::random_device rd; | |
RandomGenerator rng(rd()); | |
std::cout << "π = " << ApproximatePi(1000000, rng) << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment