Calculation of Value of Pi Using Monte-Carlo Method
Calculation of Value of Pi Using Monte-Carlo Method
Aim:
Principle:
Consider a square of side one unit as shown. Draw an arc between the points (0,1) and
(1,0).
A pair of random numbers in the range (0,1) are generated using a proper random
number generator algorithm. Representing the (x,y) points corresponding to any points
located in the figure. The following conditions are satisfied.
• 0≤𝑥≤1
• 0≤𝑦≤1
• 𝑥2 + 𝑦2 ≤ 1
Out of these three conditions, all points in the unit square considered satisfy first two
conditions. But the third condition is satisfied only by those points inside the sector.
For an unbiased random generator we can safely assume that the number of (x,y) points
generated within an area is proportional to the corresponding area. The ratio of the area of the
sector (π/4) to the area of the square would be π/4, given by the ratio the total number of
points located inside the centre (satisfying the third condition) to the total number of points
generated.Value of π could be calculated from this.
Algorithm:
Step 1: Fix N, the count of random number pairs to be generated.
Step 2: j←0
Step 4: x←random()
Step 5: y←random()
Step 6: if 𝑥 2 + 𝑦 2 ≤ 1, then
Step 7: j←j+1
Step 8: End if
Program:
j=0
for i in range(1000000):
x= random()
y= random()
if (x*x+y*y)<=1:
j=j+1
Result:
i. Trapezoidal method
Aim:
Theory:
Given a set of data points (x0,y0), (x1,y1)....(xn,yn) of a function f(x) is not known
𝑏
explicitly, it is required to compute the value of the definite integral I=∫𝑎 𝑦𝑑𝑥.
Let the interval [a,b] divided into ‘n’ equal subintervals such that
a = x0< x1<x2....<xn= b
xn = x0+nh
𝑥
I = ∫𝑥 𝑛 𝑦𝑑𝑥
0
𝑥 𝑃(𝑃−1)2 𝑃(𝑃−1)(𝑃−2)
I = ∫𝑥 𝑛[𝑦0 + p∆𝑦0 + ∆2 𝑦0 + ∆3 𝑦0 + .....]dx
0 2 6
𝑥 𝑃(𝑃−1)
I = h∫0 [𝑦0 + p∆𝑦0 + ∆2 𝑦0 +.....]dp
2
𝑛𝑥 𝑛 𝑛(2𝑛−3)2 𝑛(𝑛−2)3
∫𝑥 𝑦𝑑𝑥 = nh[y0 + 2 ∆𝑦0 + 12
∆𝑦0 + 24
∆𝑦0 +.....]
0
Setting n=1
𝑥
𝑛 ∆𝑦0 1 ℎ
∫𝑥 𝑦𝑑𝑥 = h(y0+ 2
) = h[y0 + 2(y1-y0)] = 2(y0+y1)
0
2 𝑥 ℎ
∫𝑥 𝑦𝑑𝑥 = 2(y1+y2) and so on.
1
𝑥𝑛 ℎ
∫𝑥 𝑦𝑑𝑥 = 2[yn-1 + yn]
𝑛−1
𝑛 𝑥 ℎ
∫𝑥 𝑦𝑑𝑥 = 2[y0 + 2(y1+y2+yn-1) + yn]
0
Algorithm:
Step 3: h← (b-a)/n
Step 5: x ← a+h*i
Step 6: y ← f(x(i))
ℎ
Step 7: T integral← 2[y(0)+y(-1)+2 sum (y)]
Step 9: Stop
Program:
def f(x):
return x**3-2*x*x+5
Result:
Aim:
Theory:
𝑥𝑛 𝑛 𝑛(2𝑛−3) 𝑛(𝑛−2)3
∫𝑥 𝑦𝑑𝑥 = nh[y0 + 2 ∆𝑦0 + ∆2 𝑦0 + ∆3 𝑦0 +.....]
𝑛−1 12 24
𝑛
Put n=2, ie., by replacing the curve by 2 arcs of second degree polynomials or parabola.
We have then,
𝑥 1 ℎ
∫𝑥 𝑦𝑑𝑥 = 2h(y0 + ∆y0 + 6 ∆2 y0) = 3(y0 + 4y1 + y2)
2
0
Similarly,
4𝑥 ℎ
∫𝑥 𝑦𝑑𝑥 = 3(y2 + 4y3 + y4)
2
And finally,
𝑥𝑛 ℎ
∫𝑥 𝑦𝑑𝑥 = 3(yn-2 + 4yn-1 + yn)
𝑛−2
𝑥
2 ℎ
∫𝑥 𝑦𝑑𝑥 = 3[yo +4(y1+y3+y5+....+yn-1) + 2(y2+y4+....+yn-2) + yn]
0
which is known as Simpson’s 1/3rd rule. It should be noted that this rule requires the division
of the whole range into an even number of subintervals of width h.
Algorithm:
Step 3: h ← (b-a)/n
Step 5: x ← a+h*i
Step 6: y ← f(x(i))
ℎ
Step 7: Sintegral ← 3*[y(0) + y(-1) + 4 * sum(y)[1:-1:2]+2 * sumy[2:-1:2]
Step 9: Stop
Program:
def f(x):
return x**3+5*x
a,b,n=input('Input lower limit(a), upper limit(b) & no. of steps(even no.)(n): ')
h=(b-a)/float(n)
simpint=(h/3.0)*(y[0]+y[-1]+4*sum(y[1:-1:2])+2*sum(y[2:-1:2]))
Result:
Input lower limit(a), upper limit(b) & no. of steps(even no.)(n): 1, 2,100
Aim:
Theory:
The method of least squares is probably the most systematic procedure to fit a unique
curve through given data points and is widely used in practical computations. It can also
easily implemented on a digital computer.
Let the set of data points be (xi,yi), i = 1,2...m and let the curve given by y = f(x) be
fitted to this data. At x = xi, the experimental (or observed) value of the coordinate is yi and
the corresponding value on the fitting curve is f(xi). If et is the error of approximation at x =xi,
then we have
ei = yi – f(xi)
If we write
= e12 + e22+.....+e2m
Then the method of least square consists in minimizing s, ie., the sum of the squares of the
errors.
Then,
For s to be minimum,
𝜕𝑠
= 0 = -2[y1-(a0+a1x1)] – 2[y2- (a0+a1x2)]....-2[ym-(a0+a1xm)]
𝜕𝑎0
𝜕𝑠
= 0 = -2x1[y1-(a0+a1x1)] – 2x2[y2-(a0+a1x2)].... -2xm[ym-(a0 +a1xm)]
𝜕𝑎1
The above equation simplify to
ma0 + a1∑𝑚 𝑚
𝑖=1 𝑥𝑖 = ∑𝑖=1 𝑦𝑖 ........................... (1)
And
a0∑𝑚 𝑚 2 𝑚
𝑖=1 𝑥𝑖 + a1∑𝑖=1 𝑥𝑖 = ∑𝑖=1 𝑥𝑖 𝑦𝑖
a0 + a1x = y
Where (x,y) is the centroid of given data points. It follows that the fitted straight line passes
through the centroid of data points.
Algorithm:
Step 8: p← p+x1
Step 9: q ← (q+yi)
𝑝𝑞−𝑛𝑠
Step 13: m← 𝑝2 −𝑛𝑟
𝑝𝑠−𝑞𝑟
Step 14: c← 𝑝2 −𝑛𝑟
Program:
sumx=sum(x)
sumy=sum(y)
den=n*sumxsqr-sumx*sumx
m=(n*sumxy-sumx*sumy)/float(den)
c=(sumy*sumxsqr-sumx*sumxy)/float(den)
dx=(max(x)-min(x))/float(n)
dy=(max(y)-min(y))/float(n)
axis ([min(x)-dx,max(x)+dx,min(y)-dy,max(y)+dy])
xlabel=('xdata')
ylabel('ydata')
for i in range(n):
plot(x[i],y[i],'b*')
plot(x,y1)
show()
Result:
-1,2
-2,3
-3,4
-4,5
-5,6
-6,7
Aim:
Theory:
If a function f(x) is continuous between a and b and f(a) and f(b) are of opposite
signs. Then there exists atleast one root betweeen a and b. Let f(a) be –ve and f(b) be +ve.
Then the root lies between a and b, and its approximate value be given by x0=(a+b)/2. If
f(x0)=0, then we conclude that x0 is a root of the equation. Otherwise the root lies either
between x0 and b or between x0 and a depending on whether f(x0) is –ve or +ve. We
designate the new interval as [a1, b1] whose length is |𝑏 − 𝑎|/2. As before, this is bisected at
x1 and the new interval will be exactly half the length of previous one. We repeat this process
until the last interval is small as desired, say Є. It is clear that the interval width is reduced by
a factor of one half at each step and at the end of nth step, the new interval will be [an,bn] of
|𝑏−𝑎|
length |𝑏 − 𝑎|/2n. We then have ≤Є.
2𝑛
|𝑏−𝑎|
𝑙𝑜𝑔𝑒 ( )
Which gives on simplification, n ≥ 𝑙𝑜𝑔𝑒 2
It should be noted that this method always succeeds. If there are more roots than one in the
interval, bysection method finds one of the roots. It can be easily programmed using the
following computational steps.
2) Set xr = (n+b)/2
3) i. If f(a)f(xr) ˂ 0, the root lies in the interval (a, xr). Then set b = xr and go to step 2
above.
ii. If f(a)f(xr) ˃ 0, the root lies in the interval (xr, b). Then, set a=xr and go to step 2.
iii. If f(a)f(xr) = 0, it means that xr is aroot of the equation f(x) = 0 and computation
may be terminated.
Algorithm:
Step 2: f(x)←x2-8x+2
Step 3: i←0
Step 6: x ← (a+b)/2.0
Step 7: i ← i+1
Program:
while 1:
def f(x):
return x**2-8*x+2
i=0
a=float(a)
b=float(b)
if f(a)*f(b)<0.0:
print '\nn\t\ta\t\tb\t\tf(x)'
print '-'*80
while abs(a-b)>1e-7:
x=(a+b)/2.0
i+=1
if f(x)*f(a)>0.0:
a=x
else:
b=x
print '%d\t%.8f\t%.8f\t%.8f'%(i,a,b,f(x))
break
else:
Result:
n a b f(x)
----------------------------------------------------------------
1 1.00000000 -0.50000000 6.25000000
Matrix Addition
Aim:
Principle:
Algorithm:
Program:
a=[]
for i in range(m):
row=[]
for j in range(n):
row.append(input())
a.append(row)
b=[]
for i in range(p):
row=[]
for j in range(q):
row.append(input())
b.append(row)
c=[]
for i in range(m):
row=[]
for j in range(n):
row.append(a[i][j]+b[i][j])
c.append(row)
for i in range(m):
for j in range(n):
print '%4d'%a[i][j],
for i in range(p):
for j in range(q):
print '%4d'%b[i][j],
for i in range(m):
for j in range(n):
print '%4d'%c[i][j],
else:
Result:
3
2
First matrix:
9 8
7 6
Second matrix:
5 4
3 2
Sum of matrices:
14 12
10 8
ii. Matrix addition using numpy
Algorithm:
Step 1: Enter the number of rows and columns of the first matrix m,n.
Step 2: Enter the number of rows and columns of the second matrix p,q.
Program:
a=a.reshape(m,n)
a=mat(a)
b=b.reshape(p,q)
b=mat(b)
c=a+b
else:
Result:
First matrix:
[[9 8]
[7 6]]
Second matrix:
[[1 2]
[3 4]]
[[10 10]
[10 10]]
Matrix Multiplication
Aim:
Principle:
Two matrices A and B may be multiplied together in the order of AB only when the
number of columns in A is equal to the number of rows in B. Under this condition matrices
are said to be conformable for multiplication. If matrix A is of order m*h anb of order h*n,
then the product C=AB is of order m*n. Its elements are given by,
The Cij element ie., ij element of matrix C = AB is formed as ascalar product of the i th row of
A with jth column of B. The dummy index k takes all the values 1, 2, 3,......., h in succession.
Algorithm:
Step 1: Start
Step 9: a[i][j]
Program:
if n==p:
a=a.reshape(m,n)
a=mat(a)
b=b.reshape(p,q)
b=mat(b)
c=a*b
else:
First matrix:
[[3 2]
[1 1]]
Second matrix:
[[1]
[2]]
[[7]
[3]]
iv. Matrix multiplication without numpy
Algorithm:
Step 3: If n=p
Step 8: Stop
Program:
if n==p:
a=[]
for i in range(m):
row=[]
for j in range(n):
row.append(input())
a.append(row)
b=[]
print 'Enter %d elements of second matrix one by one (row wise)'%(p*q)
for i in range(p):
row=[]
for j in range(q):
row.append(input())
b.append(row)
c=[]
for i in range(m):
row=[]
for j in range(q):
x=0
for k in range(n):
x=x+a[i][k]*b[k][j]
row.append(x)
c.append(row)
for i in range(m):
for j in range(n):
print '\t',a[i][j],
for i in range(p):
for j in range(q):
print '\t',b[i][j],
for i in range(m):
for j in range(q):
print '\t',c[i][j],
else:
Result:
First matrix:
2
Second matrix:
3 4
Product of matrices:
3 4
6 8
v. Inverse of a matrix
Aim:
Principle:
Let A be a square matrix of order n. If there exist a square matrix B of the order n
such that AB = BA = In where In is the square matrix of order n, then A is said to be invertible
and B is called the inverse of A.
𝐴𝑑𝑗 𝐴
Also, A-1 = when det A ≠0.
det 𝐴
where Adj A is the transpose of cofactor matrix Cij and cofactor Cij = (-1)i+jMIJ where Mij is
the minor of the matrix.
Mij is the determinant of the matrix elements obtained after eliminating the ith row and jth
column.
Algorithm:
Step 7: Stop
Program:
#Inverse of matrix
if m==n:
a=a.reshape(m,m)
a=mat(a)
if linalg.det(a)==0:
else:
c=a.I
else:
Result:
Matrix:
[[1 2 3]
[4 5 6]
[7 8 9]]
Aim:
Principle:
A matrix of order n*m obtained by interchanging the rows and columns of a m*n
matrix A is called the transpose of A and is denoted by the symbol AT.
ie.,
Algorithm:
Step 4: Stop
Program:
#Transpose of matrix using numpy
a=a.reshape(m,n)
a=mat(a)
b=a.T
Result:
21
35
63
45
98
75
62
98
41
[45 98 75]
[62 98 41]]
Transpose matrix:
[[21 45 62]
[35 98 98]
[63 75 41]]
Algorithm:
a=[]
for i in range(m):
row=[]
for j in range(n):
row.append(input())
a.append(row)
for i in range(m):
for j in range(n):
print '\t',a[i][j],
for i in range(n):
for j in range(m):
print '\t',a[j][i],
Result:
11
13
14
15
1 2 3 4
5 6 7 8
9 1 11 1
2 13 14 15
The transpose matrix:
1 5 9 2
2 6 1 13
3 7 11 14
4 8 1 15
Trace of a Matrix
Aim:
Principle:
Algorithm:
Step 3: Enter the matrix elements row wise and list in the matrix form.
Step 5: Stop.
Program:
if m==n:
a.reshape(m,n)
a=mat(a)
c=trace(a)
else:
Result:
-9
-5
-1.5
Given matrix:
[[-15. 4. -9. ]
[ 7. 6. -5. ]
[ 8. -1.5 7. ]]
-2.0
Algorithm:
Step 9: s←0
Program:
if m==n:
a=[]
for i in range(n):
b=[]
for j in range(n):
b.append(input())
a.append(b)
for i in range(n):
for j in range(n):
print '%4d'%a[i][j],
s=0
for i in range(n):
for j in range(n):
if i==j:
s=s+a[i][j]
else:
Result:
-4
-8
5
21
-7
51
41
-8
7 -4 -8
5 21 -7
51 41 -8
Algorithm:
Step 1: Enter the coefficients of the set of equations and form a matrix (p).
Step 2: Enter the constants of the equations and form a column matrix (q).
Step 5: End.
Program:
#a+b+c+d=4
#2a+4b+6c+8d=8
#a-3b+4c-5d=-2
#5a+2b-3c-d=5.4
p=p.reshape(4,4)
q=q.reshape(1,4)
x=linalg.solve(p,q)
print 'a=',x[0],'\nb=',x[1],'\nc=',x[2],'\nd=',x[3]
Result:
-3
-5
-3
-1
-2
5.4
Solutions are:
Aim:
To get the solution of the second order differential equation by Runge-Kutta method.
Theory:
Runge Kutta method is designed to give greater accuracy and they possess the
advantage of requiring only the function values at some selected points on the subinterval.
The fourth order Runge Kutta formula is defined by
𝑦1 = 𝑦0 + 𝑤1 𝑘1 + 𝑤2 𝑘2 + 𝑤3 𝑘3 + 𝑤4 𝑘4
where, 𝑘1 = ℎ𝑓(𝑥0 , 𝑦0 )
𝑘2 = ℎ𝑓(𝑥0 + 𝛼0 ℎ, 𝑦0 + 𝛽0 𝑘1 )
𝑘3 = ℎ𝑓(𝑥0 + 𝛼1 ℎ, 𝑦0 + 𝛽1 𝑘1 + 𝜐1 𝑘2
𝑘4 = ℎ𝑓(𝑥0 + 𝛼2 ℎ, 𝑦0 + 𝛽2 𝑘1 + 𝜐2 𝑘2 + 𝛿𝑘3
1
𝛼0 = 𝛽0 = 1/2 𝛼1 = 2𝛼 = 1 𝛽2 = 1/2(√2 − 1) 𝛽2=0
2
1 1 1
𝜐1 = 1 − √2 𝜐2 = − √2 𝛿 = 1 + √2
1 1 1 1
𝑤1 = 𝑤4 = 1/6 𝑤2 = 3 (1 − ) 𝑤3 = 3 (1 + )
√2 √2
1 1
𝛼0 = 𝛼1 = 2 𝛽0 = 𝜐1 = 2 𝛽1 = 𝛽2 = 𝜐2 = 0
𝛿2 = 𝛿1 = 1 𝑤1 = 𝑤4 = 1/6 𝑤2 = 𝑤3 = 2/6
1
𝑦1 = 𝑦0 + (𝑘1 + 2𝑘2 + 2𝑘3 + 𝑘4 )
6
where, 𝑘1 = ℎ𝑓(𝑥0 , 𝑦0 )
ℎ 𝑘1
𝑘2 = ℎ𝑓 (𝑥0 + , 𝑦0 + )
2 2
ℎ 𝑘2
𝑘3 = ℎ𝑓 (𝑥0 + , 𝑦0 + )
2 2
𝑘4 = ℎ𝑓(𝑥0 + ℎ, 𝑦0 + 𝑘3 )
Algorithm:
Step 3: h←(xf-x)/n
Step 5: 𝑘1 ← h ∗ f(x, y)
ℎ 𝑘1
Step 6: 𝑘2 ← h ∗ f(x + 2 , 𝑦 + )
2
ℎ 𝑘2
Step 7: 𝑘3 ← h ∗ f(x + 2 , 𝑦 + )
2
Step 8: 𝑘4 ← ℎ ∗ 𝑓(𝑥 + ℎ, 𝑦 + 𝑘3 )
Step 9: x←x+h
Program:
#RK method
return x*x-2*x
h=(xf-x)/float(n)
for i in range(n):
k1=h*f(x,y)
k2=h*f(x+h/2,y+k1/2)
k3=h*f(x+h/2,y+k2/2)
k4=h*f(x+h,y+k3)
x=x+h
y=y+(k1+2*(k2+k3)+k4)/6.0
Result:
Aim:
Theory:
This method is generally used to improve the result obtained by bisection method to
get roots.
Let x0 be the approximate root of f(x) =0 and let x1=x0+h be the correct root so that
f(x1)=0. Expanding f(x0+h) by Taylor series,
ℎ2
f(x0) + hf’(x0) + f”(x0) + ..... = 0
2!
f(x0) + hf’(x0) = 0
−𝑓(𝑥0 )
∴h= 𝑓 ′ (𝑥0 )
𝑓(𝑥 )
A better approximation than x0 is therefore given by x1, where x1=x0-𝑓′ (𝑥0 )
0
𝑓(𝑥 )
where xn+1 = xn- 𝑓′ (𝑥𝑛 ) which is the Newton Raphson formula.
𝑛
Algorithm:
Step 3: Read x
Step 4: While |𝑓(𝑥)| > 10-6
𝑓(𝑥)
Step 5: x ← x – 𝑓 (𝑥)
1
Step 7: Stop.
Program:
def f(x):
return x**2-2*x-1
def f1(x):
return 2*x-2
x=float(x)
while abs(f(x))>0.000001:
x=x-f(x)/f1(x)
Result: