Pure Programmer
Blue Matrix


Cluster Map

Project: Compute π (Monte Carlo with Central Limit Theorem)

Write a program that computes and prints π using the Monte Carlo method. See ComputePi2. Compute π 20 times using the Monte Carlo method and take the average to get a better approximation. Use a function to encapsulate the Monte Carlo simulation.

The idea that the average of multiple trials yields a better approximation is called the [[Central Limit Theorem]]. Is this approach any better than just computing one estimate with a larger number of samples?

Output
$ g++ -std=c++17 ComputePi4.cpp -o ComputePi4 -lfmt $ ./ComputePi4 PI0: 3.148240000000000 PI1: 3.141440000000000 PI2: 3.136080000000000 PI3: 3.143000000000000 PI4: 3.136680000000000 PI5: 3.136840000000000 PI6: 3.145880000000000 PI7: 3.144040000000000 PI8: 3.146280000000000 PI9: 3.152160000000000 PI10: 3.140240000000000 PI11: 3.137640000000000 PI12: 3.138320000000000 PI13: 3.145800000000000 PI14: 3.142680000000000 PI15: 3.138480000000000 PI16: 3.131680000000000 PI17: 3.135840000000000 PI18: 3.147560000000000 PI19: 3.147560000000000 PI: 3.141822000000000 abs(PI - π): 2.2934641021e-04

Solution