December 2, 2015

How to get approximate value of pi with Python

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

Theory: 
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.


Background:
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
    else:
        outside_circle = outside_circle + 1
pi_value = 4*inside_circle/number_of_balls
print (pi_value*1.00000)


Download 
Github at: https://github.com/evavon/approximate_pi_value_circle/blob/master/Python%20file%20for%20estimate%20pi%20value

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi Eva

    Interesting question. I have a doubt in the line
    pi_value = 4*inside_circle/number_of_balls

    Here are we calculating the fraction of the balls inside the circle (i.e. the probability) and multiplying it by the area of the square? (i.e. 4)

    ReplyDelete