# Calculate $\pi$ using Monte Carlo methods

I know that we can have an estimate of $\pi$ using Monte Carlo methods. I know that we make a huge loop and each time we take randomly two numbers in the range [0,1] and calculate the number of times this point is inside a circle of radius 1, but I don't know how to implement it using Mathematica.

So does anybody know how we implement this algorithm using Mathematica?

• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Michael E2 Apr 25 '16 at 20:29
• I would wholeheartedly recommend checking out this demonstration – gpap Apr 26 '16 at 14:32

There is an example in the documentation which may get you started:

pairs = RandomReal[{-1, 1}, {10000, 2}];
4 Count[Map[Norm, pairs], _?(# <= 1 &)]/10000.

(*3.1248*)


You can plot see this as:

Graphics[{PointSize[Small], Blue, Point@Select[pairs, Norm[#] <= 1 &],
Gray, Point@Select[pairs, Norm[#] > 1 &], Red, Thick, Circle[]}, AspectRatio -> 1]


Here is an approach using RandomPoint and graphics primitives:

pts = RandomPoint[Rectangle[], 10^6];  (* generate random points on the unit square *)
rm = RegionMember[Disk[{0.5, 0.5}, 0.5]];  (* RegionMemberFunction for an embedded Disk *)


Now we count the number of points that fall in the circle and divide that by the total number of points. That should equal the ratio of the areas of the circle to that of the square. So by multiplying by 4 we get the value of pi:

4. Count[rm[pts], True] / Length[pts]


3.1417

Visually:

Graphics[{Point[pts], Red, Point[Pick[pts, rm[pts]]]}]