December 2, 2015

How to get approximate value of pi with Python

The goal of the project is to estimate pi value without using the function math.pi.

Assuming that you throw 18,000 balls into a square of 2 feet by 2 feet. The radius of the largest circle inside the square is equal to 1. Assuming that 18,000 balls has the same probability to fall into inside the circle or outside the circle within the square. At the end, we are going to calculate number of balls inside the circle divided by 18,000 to get the approximate value of pi.

Area of circle = pi* r*r = pi*1*1 = pi
Area of square = l*l = 4

Code Python 3.0:

import random as rd
import math

inside_circle = 0
outside_circle = 0
number of balls = 18000

for i in range(0,number_of_balls):
    x = rd.random ()
    y = rd.random ()
    if math.sqrt(x*x + y*y) <= 1:
        inside_circle = inside_circle + 1
        outside_circle = outside_circle + 1
pi_value = 4*inside_circle/number_of_balls
print (pi_value*1.00000)

Github at: