|
| 1 | +''' |
| 2 | +Estimation of Pi |
| 3 | +
|
| 4 | +Write a program to compute the value of PI using a random number generator/method. |
| 5 | +
|
| 6 | +
|
| 7 | +========================================= |
| 8 | +To solve this problem we'll use the Monte Carlo simulation/method. |
| 9 | +Generate N random points (0 <= X, Y <= 1) in the first quadrant. |
| 10 | +Count all points that are inside the circle using the squared euclidean distance (between origin <0,0> and point <X,Y>). |
| 11 | +The ratio between all points in the quarter circle and quarter square should be |
| 12 | +approximately equal to the ratio between a quarter of the circle area and a quarter of the square area. |
| 13 | +(more points = better estimation) |
| 14 | +Equation: (((r^2)*PI)/4) / (((2*r)^2)/4) = circle_points / total_points |
| 15 | +Solve the first part: (((r^2)*PI)/4) / (((2*r)^2)/4) = ((1^2)*PI) / ((2*1)^2) = (1*PI) / (2^2) = PI/4 |
| 16 | +Simple equation: PI / 4 = circle_points / total_points |
| 17 | +Final form: PI = 4 * circle_points / total_points |
| 18 | + Time Complexity: O(N) |
| 19 | + Space Complexity: O(1) |
| 20 | +''' |
| 21 | + |
| 22 | + |
| 23 | +############ |
| 24 | +# Solution # |
| 25 | +############ |
| 26 | + |
| 27 | +from random import random |
| 28 | + |
| 29 | +def estimate_pi(n): |
| 30 | + total_points = 0 |
| 31 | + circle_points = 0 |
| 32 | + |
| 33 | + for i in range(n): |
| 34 | + # generate N random points in the first quadrant |
| 35 | + x, y = random(), random() |
| 36 | + |
| 37 | + if x*x + y*y <= 1: |
| 38 | + # using squared euclidean distance find the distance from (0, 0) to (x, y) |
| 39 | + circle_points += 1 |
| 40 | + total_points += 1 |
| 41 | + |
| 42 | + # this formula is a short form of this: quarter_circle_area / quarter_square_area = circle_points / total_points |
| 43 | + return 4 * circle_points / total_points |
| 44 | + |
| 45 | + |
| 46 | +########### |
| 47 | +# Testing # |
| 48 | +########### |
| 49 | + |
| 50 | +# Test 1 |
| 51 | +# Correct result => Doesn't give a good estimation at all (often the integer part is wrong) |
| 52 | +print(estimate_pi(10)) |
| 53 | + |
| 54 | +# Test 2 |
| 55 | +# Correct result => Gives a good estimation to the first decimal (3.1xxx) |
| 56 | +print(estimate_pi(10000)) |
| 57 | + |
| 58 | +# Test 3 |
| 59 | +# Correct result => Gives a good estimation to the second decimal (3.14xxx) |
| 60 | +print(estimate_pi(10000000)) |