Last active
March 4, 2017 04:26
-
-
Save mjkoo/a7be0244f61fa0ddeaa50261d69f1802 to your computer and use it in GitHub Desktop.
Estimate pi
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 <cmath> | |
#include <iomanip> | |
#include <iostream> | |
#include <random> | |
struct point { | |
double x, y; | |
inline double distance_squared() const | |
{ | |
return x * x + y * y; | |
} | |
inline bool hits_circle(double radius_squared) const | |
{ | |
return distance_squared() < radius_squared; | |
} | |
}; | |
point make_random_point(double radius) | |
{ | |
static std::random_device rd; | |
static std::mt19937 rng{ rd() }; | |
std::uniform_real_distribution<> dist{ -radius, radius }; | |
return point{ dist(rng), dist(rng) }; | |
} | |
double estimate_pi(unsigned int n, unsigned int m) | |
{ | |
double radius = std::pow(10, n); | |
double radius_squared = radius * radius; | |
unsigned int num_samples = std::pow(10, m); | |
unsigned int num_hits = 0; | |
for (unsigned int i = 0; i < num_samples; ++i) { | |
auto sample = make_random_point(radius); | |
if (sample.hits_circle(radius_squared)) | |
++num_hits; | |
} | |
return static_cast<double>(num_hits) / num_samples * 4; | |
} | |
constexpr double distance_from_pi(double estimate) | |
{ | |
constexpr double pi = 3.14159265359; | |
return std::abs(estimate - pi); | |
} | |
int main(int argc, char** argv) | |
{ | |
for (unsigned int n = 0; n <= 9; ++n) { | |
for (unsigned int m = 0; m <= 7; ++m) | |
std::cout << std::setw(12) << distance_from_pi(estimate_pi(n, m)); | |
std::cout << std::endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment