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
$ javac -Xlint ComputePi4.java
$ java -ea ComputePi4
PI0: 3.141400000000000
PI1: 3.141480000000000
PI2: 3.135720000000000
PI3: 3.149040000000000
PI4: 3.140120000000000
PI5: 3.145400000000000
PI6: 3.150000000000000
PI7: 3.140160000000000
PI8: 3.138680000000000
PI9: 3.136560000000000
PI10: 3.138200000000000
PI11: 3.144160000000000
PI12: 3.147160000000000
PI13: 3.134440000000000
PI14: 3.142960000000000
PI15: 3.135600000000000
PI16: 3.137120000000000
PI17: 3.145680000000000
PI18: 3.139760000000000
PI19: 3.153480000000000
PI: 3.141856000000000
abs(PI - π): 2.6334641021e-04