Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pi estimator
#include <algorithm>
#include <cmath>
#include <iostream>
#include <random>
#include <vector>
using point_t = std::pair<double, double>;
std::vector<point_t> generateRandomPointsInSquare(double length, size_t nbPoints) {
std::random_device random_device;
auto engine = std::mt19937{random_device()};
auto x_dist = std::uniform_real_distribution<double>{-length, length};
auto y_dist = std::uniform_real_distribution<double>{-length, length};
auto points = std::vector<point_t>(nbPoints);
std::generate_n(points.begin(), nbPoints,
[&x_dist, &y_dist, &engine]() { return std::make_pair(x_dist(engine), y_dist(engine)); });
return points;
}
bool inCircle(const point_t& pt, double radius) {
return pt.first * pt.first + pt.second * pt.second <= radius * radius;
}
double estimatePi(int n, int m) {
const auto radius = std::pow(10.0, n);
const auto nbPoints = static_cast<size_t>(std::pow(10, m));
const auto points = generateRandomPointsInSquare(radius, nbPoints);
const auto nbPointsInCircle =
std::count_if(points.cbegin(), points.cend(), [radius](const point_t& pt) { return inCircle(pt, radius); });
return 4 * static_cast<double>(nbPointsInCircle) / static_cast<double>(nbPoints);
}
double computeError(double estimate) {
constexpr auto PI = double{3.14159265359};
return std::abs(estimate - PI);
}
int main(int argc, const char* argv[]) {
for (auto n = 0; n <= 9; ++n) {
for (auto m = 0; m <= 7; ++m) {
std::cout << computeError(estimatePi(n, m)) << ' ';
}
std::cout << '\n';
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment