Last active
March 4, 2017 13:16
-
-
Save BiCapitalization/dd4b21a875fd44a644cf8d90fdc4f2a6 to your computer and use it in GitHub Desktop.
Entry for the Pi Day Challenge (http://www.fluentcpp.com/2017/03/02/the-pi-day-challenge-for-expressive-code-in-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
/* | |
*This program approximates pi using the monte carlo method of counting how | |
*many points in a square fall into a circle inscribed in it. | |
* | |
*The program outputs the deviation from pi for a circle radius from 1 to 10^9 | |
*and a number of points from 1 to 10^7, where consecutive rows represent an | |
*increase in radius by one power of 10 each and consecutive columns represent | |
*an increase in number of points by one power of 10, respectively. | |
* | |
*Author: Ben Steffan | |
*Date: 04.03.2017 | |
*/ | |
#include <iostream> | |
#include <iomanip> | |
#include <vector> | |
#include <cmath> | |
#include <utility> | |
#include <random> | |
#include <algorithm> | |
double calculate_pi_approximation(unsigned radius, unsigned count, | |
std::mt19937& rand_engine) { | |
using namespace std; | |
uniform_real_distribution<double> dist(-(double) (radius), radius); | |
vector<pair<double, double>> points(count); | |
generate(points.begin(), points.end(), [&] () { | |
return make_pair(dist(rand_engine), dist(rand_engine)); | |
}); | |
size_t in_circle = count_if(points.cbegin(), points.cend(), | |
[&] (auto point) { | |
return sqrt(pow(get<0>(point), 2) + pow(get<1>(point), 2)) | |
<= radius; | |
}); | |
double pi_approximation = (double) (in_circle) / count * 4.0; | |
return pi_approximation; | |
} | |
int main() { | |
const double pi = 3.14159265359; | |
std::random_device rnd; | |
std::mt19937 engine(rnd()); | |
for (unsigned radius_power = 0; radius_power <= 9; ++radius_power) { | |
for (unsigned count_power = 0; count_power <= 7; ++count_power) { | |
double approximation = calculate_pi_approximation( | |
std::pow(10, radius_power), | |
std::pow(10, count_power), engine); | |
double deviation = std::abs(pi - approximation); | |
std::cout << std::setw(12) << deviation; | |
} | |
std::cout << '\n'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment