#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. //Approximately 78% of the random points will fall within the unit circle. // //Each time we use the expression r(), it gives us a different random number //in the range -1.0 to +1.0 //CISC-2000-E01 will explain how we created r. int main() { 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 n {1000}; //Will a higher n give us a more accurate answer? int count {0}; //How many random points were in the unit circle for (int i = 0; i < n; ++i) { //Pick a random point (x, y) in the square. double x {r()}; double y {r()}; //if the point (x, y) is within the unit circle, if (sqrt(x*x + y*y) < 1.0) { ++count; } } //area of the 2 by 2 square that encloses the unit circle double square {2.0 * 2.0}; cout << count << " out of " << n << " points fell within the circle.\n" << "That's " << 100.0 * count / n << " percent of the points.\n" << fixed << setprecision(5) << "The area of the square is " << square << "\n" << "The area of the circle is " << square * count / n << "\n"; return EXIT_SUCCESS; }