Created
April 28, 2017 22:47
-
-
Save MehdiNS/3281e007a2eb8b91d45a70e3dbb94031 to your computer and use it in GitHub Desktop.
Value of Pi computed using Monte Carlo
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 <vector> | |
#include <random> | |
#include <string> | |
#include <cmath> | |
#include <chrono> | |
using namespace std; | |
using namespace std::chrono; | |
struct Point2 | |
{ | |
float x, y; | |
}; | |
float distance(Point2 center, Point2 point) | |
{ | |
float cpx = (center.x - point.x); | |
float cpy = (center.y - point.y); | |
return sqrt(cpx*cpx + cpy*cpy); | |
} | |
bool isInCircle(Point2 center, float radius, Point2 point) | |
{ | |
return distance(center, point) <= radius; | |
} | |
int main() | |
{ | |
const unsigned int NB_SAMPLES = 10'000'000; | |
const float sizeSquare = 2.; | |
const float areaSquare = sizeSquare * sizeSquare; | |
const float radius = 0.5*sizeSquare; | |
const Point2 center = { radius,radius }; | |
random_device r; | |
default_random_engine e1(r()); | |
uniform_real_distribution<float> uniform_dist(0.f, sizeSquare); | |
unsigned int count = 0; | |
float estimatedPi; | |
auto before = system_clock::now(); | |
for (unsigned int i = 0; i < NB_SAMPLES; ++i) | |
{ | |
// Generate a 2d point sample in [0,sizeSquare]x[0,sizeSquare] | |
// Add to counter if the sample is in circle | |
if (isInCircle(center, radius, { uniform_dist(e1) , uniform_dist(e1) })) | |
count++; | |
// Current Pi estimation | |
estimatedPi = areaSquare * static_cast<float>(count) / static_cast<float>(i); | |
// cout << "Estimated Pi : " << estimatedPi << "\n"; | |
} | |
auto after = system_clock::now(); | |
auto deltaTime = duration_cast<seconds>(after - before).count(); | |
cout << "Estimated Pi : " << estimatedPi << " computed in " << deltaTime << " seconds" << "\n"; | |
cin >> estimatedPi; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment