Pure Programmer
Blue Matrix

Cluster Map

Project: Compute π (Monte Carlo)

You can compute π (rather inefficiently) without using any trigonometric functions. By using a method called the Monte Carlo method, which generates a lot of random samples, we can approximate the value of π. If we take a square with sides of one unit and randomly generate X and Y values within the square, we can then keep track of the ones that are within one unit radius of the origin (0,0). The ratio of samples inside the quarter cirle to the total number of samples approximates the quarter circle area of the enclosing square which is π/4. Write a program that computes and prints π using the Monte Carlo method.

See [[Monte Carlo Method]]

$ g++ -std=c++17 ComputePi2.cpp -o ComputePi2 -lfmt $ ./ComputePi2 pi: 3.141636000000000 abs(pi - π): 4.3346410207e-05