#include #include //for setprecision #include #include //for chrono::system_clock #include //for default_random_engine #include //for bind using namespace std; //Approximate the value of pi by a Monte Carlo method. double pi(int n); int main() { int a[] { //how many random points to generate 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000, 100000, 500000 }; int n {size(a)}; //how many numbers are in the array cout << " n pi error\n"; //column headings for (int i {0}; i < n; ++i) { double p {pi(a[i])}; //the approximate value of pi cout << setw(6) << a[i] << " " << fixed << setprecision(5) << p << " " << abs(3.14159265358979323846 - p) << "\n"; //absolute } return EXIT_SUCCESS; } //Return an approximation to the value of pi, counting how many of n //random points lie within the unit circle. double pi(int n) { unsigned seed = chrono::system_clock::now().time_since_epoch().count(); default_random_engine engine {seed}; uniform_real_distribution distribution {-1.0, 1.0}; auto r {bind(distribution, engine)}; int count {0}; //How many random points were in the unit circle for (int i = 0; i < n; ++i) { //Pick random point (x, y) in square enclosing the unit circle. double x {r()}; double y {r()}; //if the point (x, y) is within the unit circle, if (x*x + y*y < 1.0) { ++count; } } return 4.0 * count / n; //4.0 is the area of the enclosing square }