from math import pi,sqrt
import random
import matplotlib.pyplot as plt
import numpy as np
The number $\pi$ is a mathematical constant. Originally defined as the ratio of a circle's circumference to its diameter, it now has various equivalent definitions and appears in many formulas in all areas of mathematics and physics. It is approximately equal to 3.14159. It has been represented by the Greek letter "$\pi$" since the mid-18th century, though it is also sometimes spelled out as "pi". It is also called Archimedes' constant.
Being an irrational number, $\pi$ cannot be expressed as a common fraction (equivalently, its decimal representation never ends and never settles into a permanently repeating pattern).
print("Value of pi: ",pi)
Value of pi: 3.141592653589793
Imagine a square dartboard.
Then, the dartboard with a circle drawn inside it touching all its sides.
And then, you throw darts at it. Randomly. That means some fall inside the circle, some outside. But assume that no dart falls outside the board.
At the end of your dart throwing session, you count the fraction of darts that fell inside the circle of the total number of darts thrown. Multiply that number by 4.
The resulting number should be pi. Or, a close approximation if you had thrown a lot of darts.
The idea is extremely simple. If you throw a large number of darts, then the probability of a dart falling inside the circle is just the ratio of the area of the circle to that of the area of the square board. With the help of basic mathematics, you can show that this ratio turns out to be pi/4. So, to get pi, you just multiply that number by 4.
The key here is to simulate the throwing of a lot of darts so as to make the fraction equal to the probability, an assertion valid only in the limit of a large number of trials of this random event. This comes from the law of large number or the frequentist definition of probability.
See also the concept of Buffon's Needle
# Center point
x,y = 0,0
# Side of the square
a = 2
def throw_dart():
"""
Simulates the randon throw of a dirt. It can land anywhere in the square (uniformly randomly)
"""
# Random final landing position of the dirt between -a/2 and +a/2 around the center point
position_x = x+a/2*(-1+2*random.random())
position_y = y+a/2*(-1+2*random.random())
return (position_x,position_y)
throw_dart()
(0.21862368906636753, 0.04575803244910337)
def is_within_circle(x,y):
"""
Given the landing coordinate of a dirt, determines if it fell inside the circle
"""
# Side of the square
a = 2
distance_from_center = sqrt(x**2+y**2)
if distance_from_center < a/2:
return True
else:
return False
is_within_circle(1.9,1.9)
False
is_within_circle(1.2,1.9)
False
is_within_circle(0.4,-0.74)
True
r1,r2=throw_dart()
print(r1,r2)
if is_within_circle(r1,r2):
print("This one landed inside the circle!")
else:
print("This one did not land inside the circle!")
-0.5129931631226134 0.3782598009424025 This one landed inside the circle!
n_throws = 10
count_inside_circle=0
for i in range(n_throws):
r1,r2=throw_dart()
if is_within_circle(r1,r2):
count_inside_circle+=1
count_inside_circle
and n_throws
¶ratio = count_inside_circle/n_throws
print(4*ratio)
3.2
n_throws = 10000
count_inside_circle=0
for i in range(n_throws):
r1,r2=throw_dart()
if is_within_circle(r1,r2):
count_inside_circle+=1
ratio = count_inside_circle/n_throws
print(4*ratio)
3.1476
def compute_pi_throwing_dart(n_throws):
"""
Computes pi by throwing a bunch of darts at the square
"""
n_throws = n_throws
count_inside_circle=0
for i in range(n_throws):
r1,r2=throw_dart()
if is_within_circle(r1,r2):
count_inside_circle+=1
result = 4*(count_inside_circle/n_throws)
return result
n_exp=[]
pi_exp=[]
n = [int(10**(0.5*i)) for i in range(1,15)]
for i in n:
p = compute_pi_throwing_dart(i)
pi_exp.append(p)
n_exp.append(i)
print("Computed value of pi by throwing {} darts is: {}".format(i,p))
Computed value of pi by throwing 3 darts is: 2.6666666666666665 Computed value of pi by throwing 10 darts is: 4.0 Computed value of pi by throwing 31 darts is: 3.3548387096774195 Computed value of pi by throwing 100 darts is: 3.16 Computed value of pi by throwing 316 darts is: 3.1645569620253164 Computed value of pi by throwing 1000 darts is: 3.148 Computed value of pi by throwing 3162 darts is: 3.135989879822897 Computed value of pi by throwing 10000 darts is: 3.1736 Computed value of pi by throwing 31622 darts is: 3.1553981405350706 Computed value of pi by throwing 100000 darts is: 3.14972 Computed value of pi by throwing 316227 darts is: 3.143653135247781 Computed value of pi by throwing 1000000 darts is: 3.144012 Computed value of pi by throwing 3162277 darts is: 3.141502151772283 Computed value of pi by throwing 10000000 darts is: 3.1412476
plt.figure(figsize=(8,5))
plt.title("Computing pi with \nincreasing number of random throws",fontsize=20)
plt.semilogx(n_exp, pi_exp,c='k',marker='o',lw=3)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xlabel("Number of random throws",fontsize=15)
plt.ylabel("Computed value of pi",fontsize=15)
plt.hlines(y=3.14159,xmin=1,xmax=1e7,linestyle='--')
plt.text(x=10,y=3.05,s="Value of pi",fontsize=17)
plt.grid(True)
plt.show()
n = 5000000
sum=0
for i in range(20):
p=compute_pi_throwing_dart(n)
sum+=p
print("Experiment number {} done. Computed value: {}".format(i+1,p))
print("-"*75)
pi_computed = round(sum/20,4)
print("Average value from 20 experiments:",pi_computed)
Experiment number 1 done. Computed value: 3.1411944 Experiment number 2 done. Computed value: 3.1404488 Experiment number 3 done. Computed value: 3.1419368 Experiment number 4 done. Computed value: 3.1427144 Experiment number 5 done. Computed value: 3.1412816 Experiment number 6 done. Computed value: 3.141308 Experiment number 7 done. Computed value: 3.1412728 Experiment number 8 done. Computed value: 3.1412608 Experiment number 9 done. Computed value: 3.1424392 Experiment number 10 done. Computed value: 3.1415536 Experiment number 11 done. Computed value: 3.1418888 Experiment number 12 done. Computed value: 3.1413784 Experiment number 13 done. Computed value: 3.141464 Experiment number 14 done. Computed value: 3.1418816 Experiment number 15 done. Computed value: 3.141988 Experiment number 16 done. Computed value: 3.1420944 Experiment number 17 done. Computed value: 3.1415448 Experiment number 18 done. Computed value: 3.1422472 Experiment number 19 done. Computed value: 3.142232 Experiment number 20 done. Computed value: 3.14278 --------------------------------------------------------------------------- Average value from 20 experiments: 3.1417
error_pct = 100*(pi - pi_computed)/pi
print("Error percentage: ", error_pct)
Error percentage: -0.0034169423615242416