Python and Turtle animation,Difficulty Level 7,loop,math,python,random Estimating π with Monte Carlo Method

Estimating π with Monte Carlo Method

Monte Carlo Methods are interesting algorithms that rely on random sampling to obtain numeric result (Wikipedia). Since today is Pi Day, we are going to design a Monte Carol method to estimate the value of π.

Draw a 800*800 square on canvas. Randomly generate a coordinate (x,y) that falls inside this square and draw a small point (using Turtle’s dot() function) on this position. If this point’s distance to lower left corner of the square is less than 800, draw this point with blue color. If the distance equals to 800, draw this point with blue or red color with 50% chance each. Otherwise, draw this point with red color. Keep generating this point a lot times as you keep count of red points and blue points.

Since the area of the quarter circle to the square is π/4. The ratio blue over the total number points times 4 should estimate the value of π.

Estimating π with Monte Carlo Method – Python Turtle Project

Related Post