Created
March 13, 2017 03:16
-
-
Save vineethviswan/2d5790ba6a5e171d3c74b3fac84221fd to your computer and use it in GitHub Desktop.
Pi Day Challenge - Fluent C++
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
/* | |
Pi Estimation using Monte Carlo method. | |
Author - Vineeth | |
Date - 03/12/2017 | |
Ref : http://www.fluentcpp.com/2017/03/02/the-pi-day-challenge-for-expressive-code-in-c/ | |
*/ | |
#include <iostream> | |
#include <random> | |
#include <math.h> | |
#include <iomanip> | |
using namespace std; | |
const double piReference = 3.14159265359; | |
bool pointsInCircle(const pair<double, double> pt, double mRadius) { | |
if (pow(pt.first, 2) + pow(pt.second, 2) <= pow(mRadius, 2)) | |
return true; | |
return false; | |
} | |
long double getPiVariance(double mRadius, int32_t mPointsCount) { | |
random_device mRandom; | |
mt19937 rnEngine(mRandom()); | |
uniform_real_distribution<double> mDistribution(-1 * mRadius, mRadius); | |
int mPointsInCircle = 0; | |
for (long i = 0; i < mPointsCount; i++) { | |
double x = mDistribution(rnEngine); | |
double y = mDistribution(rnEngine); | |
if (pointsInCircle(make_pair(x, y), mRadius)) | |
mPointsInCircle++; | |
} | |
long double pi = 4 * static_cast<double>(mPointsInCircle) / static_cast<double>(mPointsCount); | |
return abs(piReference - pi); | |
} | |
void printPiVariance() { | |
double mRadius; | |
int32_t mPointsCount; | |
for (int n = 0; n <= 9; n++) { | |
for (int m = 0; m <= 7; m++) { | |
mRadius = pow(10, n); | |
mPointsCount = static_cast<int>(pow(10, m)); | |
cout << setw(15) << getPiVariance(mRadius, mPointsCount); | |
} | |
cout << endl; | |
mRadius = 0.0; | |
mPointsCount = 0; | |
} | |
} | |
int main() { | |
printPiVariance(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment