You are on page 1of 54

Calculation of value of pi using Monte-Carlo Method

Aim:

To find the value of pi using random numbers.

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 3: for i=1 to N do

Step 4: x←random()

Step 5: y←random()

Step 6: if 𝑥 2 + 𝑦 2 ≤ 1, then

Step 7: j←j+1

Step 8: End if

Step 9: End for

Step 10: pi←4*j/i

Step 11: print pi

Step 12: Stop

Program:

from random import *

j=0

for i in range(1000000):

x= random()

y= random()

if (x*x+y*y)<=1:

j=j+1

print 'Value of pi= ',4.0*j/i

Result:

Value of pi= 3.14158314158


Numerical Integration

i. Trapezoidal method

Aim:

To get the solution of numerical integration using trapezoidal method.

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=∫𝑎 𝑦𝑑𝑥.

As in the case of numerical differentiation one replaces f(x) by an interpolating


polynomial ∅(x) and obtains on integration, an approximate value of the definite integral.
Thus different integration formulae can be obtained depending upon the type of the
interpolation formulae used.

Let the interval [a,b] divided into ‘n’ equal subintervals such that

a = x0< x1<x2....<xn= b

xn = x0+nh

Hence the integral becomes,

𝑥
I = ∫𝑥 𝑛 𝑦𝑑𝑥
0

Approximating by Newton’s forward difference formula, we obtain xn.

𝑥 𝑃(𝑃−1)2 𝑃(𝑃−1)(𝑃−2)
I = ∫𝑥 𝑛[𝑦0 + p∆𝑦0 + ∆2 𝑦0 + ∆3 𝑦0 + .....]dx
0 2 6

Since x=xo+ph, dx=hdp and hence the above integral becomes,

𝑥 𝑃(𝑃−1)
I = h∫0 [𝑦0 + p∆𝑦0 + ∆2 𝑦0 +.....]dp
2

Which gives on simplification

𝑛𝑥 𝑛 𝑛(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

For the next interval [x1, x2], we deduce similarly

2 𝑥 ℎ
∫𝑥 𝑦𝑑𝑥 = 2(y1+y2) and so on.
1

For the last interval [xn-1, xn], we have

𝑥𝑛 ℎ
∫𝑥 𝑦𝑑𝑥 = 2[yn-1 + yn]
𝑛−1

Combining all these expressions, we obtain the rule

𝑛 𝑥 ℎ
∫𝑥 𝑦𝑑𝑥 = 2[y0 + 2(y1+y2+yn-1) + yn]
0

Which is known as trapezoidal rule.

Algorithm:

Step 1: Define f(x)

Step 2: Read a,b,n

Step 3: h← (b-a)/n

Step 4: for i=1 to n+1

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 8: Print integral using Trapezoidal rule.

Step 9: Stop

Program:

def f(x):

return x**3-2*x*x+5

a,b,n=input('Input lower limit(a), upper limit(b) & no. of steps(n): ')


h=(b-a)/float(n)

x=[a+h*i for i in range(n+1)]

y=[f(x[i]) for i in range(n+1)]

trapint=(h/2.0)*(y[0]+ y[-1]+ 2*sum(y[1:-1:1]))

print 'Integral using trapezoidal method= ',trapint

Result:

Input lower limit(a), upper limit(b) & no. of steps(n): 1,5,100

Integral using trapezoidal method= 93.3408

ii. Simpson’s 1/3rd Rule

Aim:

To get the solution of numerical integration by Simpson’s 1/3rd rule.

Theory:

We have the general formula of integation,

𝑥𝑛 𝑛 𝑛(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

Summing up, we obtain

𝑥
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 1: Define f(x)

Step 2: Read a,b,n

Step 3: h ← (b-a)/n

Step 4: for I = 1 to n+1

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 8: Print integral using Simpson’s rule

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)

x=[a+h*i for i in range(n+1)]


y=[f(x[i]) for i in range(n+1)]

simpint=(h/3.0)*(y[0]+y[-1]+4*sum(y[1:-1:2])+2*sum(y[2:-1:2]))

print 'Integral using Simpson\'s 1/3 rule= ', simpint

Result:

Input lower limit(a), upper limit(b) & no. of steps(even no.)(n): 1, 2,100

Integral using Simpson's 1/3 rule= 11.25


Least Square Curve Fitting

Aim:

To obtain the slope and intercept by Least Square Fit.

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

s = [y1 - f(x1)]2 + [y2 - f(x2)]2 +.....+ [ym-f(xm)]2.

= e12 + e22+.....+e2m

Then the method of least square consists in minimizing s, ie., the sum of the squares of the
errors.

Fitting a straight line:

Let y = a0+a1x be the straight line to be fitted to the given data.

Then,

s = [y1- (a0+a1x1)] 2 + [y2-(a0+a1x2)]2 +.....+ [ym-(a0+a1xm)]2

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(x1+x2+.....+xm) = y1+y2+....+ym

and a0(x1+x2+....+xm) + a1(x12+x22+....+xm2) = x1y1 + x2y2 +....+xmym

or more compactly to,

ma0 + a1∑𝑚 𝑚
𝑖=1 𝑥𝑖 = ∑𝑖=1 𝑦𝑖 ........................... (1)

And

a0∑𝑚 𝑚 2 𝑚
𝑖=1 𝑥𝑖 + a1∑𝑖=1 𝑥𝑖 = ∑𝑖=1 𝑥𝑖 𝑦𝑖

Further dividing equation (1) throughout by m, we get

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 1: Read number of data points n.

Step 2: Sum of x values p←0

Step 3: sum of y values q←0

Step 4: sum of x2 values r←0

Step 5: sum of xy values s←0

Step 6: for i = 1 to n do.

Step 7: read pair (xi,yi)

Step 8: p← p+x1

Step 9: q ← (q+yi)

Step 10: r ← r+xi2

Step 11: s ← s+xiyi


Step 12: End for

𝑝𝑞−𝑛𝑠
Step 13: m← 𝑝2 −𝑛𝑟

𝑝𝑠−𝑞𝑟
Step 14: c← 𝑝2 −𝑛𝑟

Step 15: Print m and c

Step 16: Plot x and y value

Step 17: For i=1 to n do

Step 18: End for

Step 19: Plot xi,yi value

Step 20: End

Program:

from pylab import*

n=input('No. of data value(x,y) pairs: ')

print 'Enter %d(x,y) pairs one by one: '%n

xy=[input() for i in range(n)]

x=[xy[i][0] for i in range(n)]

y=[xy[i][1] for i in range(n)]

sumx=sum(x)

sumy=sum(y)

sumxsqr=sum([i*i for i in x])

sumxy=sum(x[i]*y[i] for i in range(n))

den=n*sumxsqr-sumx*sumx

m=(n*sumxy-sumx*sumy)/float(den)
c=(sumy*sumxsqr-sumx*sumxy)/float(den)

print '\nSlope(m)= ',m,'y-intercept(c)= ',c

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])

title('Linear least square fit')

xlabel=('xdata')

ylabel('ydata')

for i in range(n):

plot(x[i],y[i],'b*')

y1=[(m*x[i]+c) for i in range(n)]

plot(x,y1)

show()

Result:

No. of data value(x,y) pairs: 6

Enter 6(x,y) pairs one by one:

-1,2

-2,3

-3,4

-4,5

-5,6

-6,7

Slope(m)= -1.0 y-intercept(c)= 1.0


Bolzano’s Bisection Method

Aim:

To get the solution of algebraic equation by bisection method.

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

This inequality gives the number of iterations required to achieve an accuracy.

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.

1) Choose two real numbers a and b such that f(a)f(b)˂ 0.

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 1: Read a,b

Step 2: f(x)←x2-8x+2

Step 3: i←0

Step 4: If f(a)*f(b) ˂ 0.0, print n,a,b,f(x)

Step 5: While |𝑎 − 𝑏| ≥ 0.00000001 do

Step 6: x ← (a+b)/2.0

Step 7: i ← i+1

Step 8: If f(x)*f(a) ˃ 0.00 then a← x else x1← x2 end.

Step 9: Print no roots in this interval.

Step 10: Print ‘Enter another interval’.

Step 11: Stop.

Program:

#Solution for transcendental equation

while 1:

a,b=input('Enter the interval a,b: ')

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))

print '\nThe correct solution is ',x

break

else:

print 'No roots in this interval'

print 'Enter another interval'

Result:

Enter the interval a,b: 2,5

No roots in this interval

Enter another interval

Enter the interval a,b: 1,-2

n a b f(x)

----------------------------------------------------------------
1 1.00000000 -0.50000000 6.25000000

2 1.00000000 0.25000000 0.06250000

3 0.62500000 0.25000000 -2.60937500

4 0.43750000 0.25000000 -1.30859375

5 0.34375000 0.25000000 -0.63183594

6 0.29687500 0.25000000 -0.28686523

7 0.27343750 0.25000000 -0.11273193

8 0.26171875 0.25000000 -0.02525330

9 0.26171875 0.25585938 0.01858902

10 0.25878906 0.25585938 -0.00334072

11 0.25878906 0.25732422 0.00762200

12 0.25878906 0.25805664 0.00214010

13 0.25842285 0.25805664 -0.00060044

14 0.25842285 0.25823975 0.00076980

15 0.25842285 0.25833130 0.00008467

16 0.25837708 0.25833130 -0.00025789

17 0.25835419 0.25833130 -0.00008661

18 0.25834274 0.25833130 -0.00000097

19 0.25834274 0.25833702 0.00004185

20 0.25834274 0.25833988 0.00002044

21 0.25834274 0.25834131 0.00000973

22 0.25834274 0.25834203 0.00000438

23 0.25834274 0.25834239 0.00000171


24 0.25834274 0.25834256 0.00000037

25 0.25834265 0.25834256 -0.00000030


Matrix Operations

Matrix Addition

Aim:

To find the sum of two matrices.

Principle:

A matrix may be defined as a square or a rectangular array of numbers or functions


that obeys certain laws. The individual numbers of the array are called the elements of the
matrix. The two matrices A and B are said to be conformable for addition if they have same
order. If there are two matrices A=[aij] and B=[bij], each of order m*n, then the sum of two
matrices A and B is defined as the matrix C=[cij] of order m*n , each element of which is the
sum of corresponding elements of A and B.

ie., A+B=C if and only if aij+bij=cij for all values of i and j.

i. Matrix addition without numpy

Algorithm:

Step 1: m,n ← Read the order of first matrix.

Step 2: p,q ← Read the order of second matrix.

Step 3: Else go to step 23.

Step 4: i←0, j←0 if m=p and n=q then go to step 4.

Step 5: If i˂m, then go to step 6, else go to step 10.

Step 6: If j˂n, then go to step 7, else go to step 9.

Step 8: j←j+1, go to step 6

Step 9: i←i+1, go to step 11

Step 10: i←0, j←0


Step 11: If i˂m, then go to step 12, else go to step 16.

Step 12: If j˂n, then go to step 14, else go to step 15.

Step 13: Read elements of second matrix.

Step 14: j←j+1, go to step 12

Step 15: i←i+1, go to step 11

Step 16: i←0, j←0

Step 17: If i˂m, then go to step 18, else go to step 24.

Step 18: If j˂n, then go to step 19, else go to step 12

Step 19: S[i][j] = a[i][j] + b[i][j]

Step 20: Print S[i][j]

Step 21: j←j+1, go to step 18

Step 22: i←i+1, go to step 17

Step 23: Print matrix addition is not possible.

Step 24: Stop

Program:

#Matrix addition without numpy

m,n=input('Order of the first matrix: ')

p,q=input('Order of the second matrix: ')

if m==p and n==q:

a=[]

print 'Enter %d elements of first matrix one by one (row wise)'%(m*n)

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(n):

row.append(a[i][j]+b[i][j])

c.append(row)

print '\n First matrix: \n'

for i in range(m):

for j in range(n):

print '%4d'%a[i][j],

print

print '\n Second matrix: \n'

for i in range(p):
for j in range(q):

print '%4d'%b[i][j],

print

print '\n Sum of matrices: \n'

for i in range(m):

for j in range(n):

print '%4d'%c[i][j],

print

else:

print 'Not compatible for addition'

Result:

Order of the first matrix: 2,2

Order of the second matrix: 2,2

Enter 4 elements of first matrix one by one (row wise)

Enter 4 elements of second matrix one by one (row wise).

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.

Step 3: If m=p and n=q, then enter elements of first matrix.

Step 4: Enter elements of second matrix.

Step 5: Add corresponding elements.

Step 6: Print the sum of two matrices.

Step 7: Else print matrix addition is not possible.

Program:

#Matrix addition using numpy

from numpy import *

m,n=input('Order of the first matrix: ')

p,q=input('Order of the second matrix: ')

if m==p and n==q:

print 'Enter %d elements of the first matrix (row wise) '%(m*n)

a=array([input() for i in range (m*n)])

a=a.reshape(m,n)

a=mat(a)

print 'Enter %d elements of the second matrix (row wise) '%(p*q)

b=array([input() for i in range (p*q)])

b=b.reshape(p,q)

b=mat(b)
c=a+b

print ' First matrix: \n',a

print ' Second matrix: \n',b

print 'Sum of the matrices: \n',c

else:

print 'Matrix addition is not possible'

Result:

Order of the first matrix: 2,2

Order of the second matrix: 2,2

Enter 4 elements of the first matrix (row wise)

Enter 4 elements of the second matrix (row wise)

First matrix:

[[9 8]

[7 6]]

Second matrix:
[[1 2]

[3 4]]

Sum of the matrices:

[[10 10]

[10 10]]

Matrix Multiplication

Aim:

To find the product of two matrices.

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,

Cij =∑hk=1 𝑎𝑖𝑘 bkj

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.

iii. Matrix multiplication using numpy

Algorithm:

Step 1: Start

Step 2: Read m and n, the order of first matrix.


Step 3: Read p and q, the order of second matrix.

Step 4: If n≠p, then print multiplication is not possible.

Step 5: Set i←0

Step 6: Repeat step 7 through 11 until i˂m.

Step 7: Set j←0

Step 8: Repeat step 9 through 10 until j˂n.

Step 9: a[i][j]

Step 10: j←j+1

Step 11: i←i+1

Step 12: Set i←0

Step 13: Repeat step 14 through 18 until i<p.

Step 14: Set j←0

Step 15: Repeat step 16 through 17 until j<q.

Step 16: Read b[i][j]

Step 17: j←j+1

Step 18: i←i+1

Step 19: Set i←0

Step 20: Repeat step 21 through 29 unti i<m

Step 21: Set j←0

Step 22: Repeat step 23 through 28 until j<q

Step 23: k←0

Step 24: c[i][j] ←0

Step 25: Repeat step 26 through 27 until k<n


Step 26: c[i][j] ←c[i][j] + a[i][j] * b[i][j]

Step 27: k←k+1

Step 28: j←j+1

Step 29: i←i+1

Step 30: Set i←0

Step 31: Repeat step 32 through 36 until i<m

Step 32: Set j←0

Step 33: Repeat step 34 through 35 until j<n

Step 34: Print a[i][j]

Step 35: j←j+1

Step 36: i←i+1

Step 37: Set i←0

Step 38: Repeat step 39 through 43 until i˂p

Step 39: Set j←0

Step40: Repeat sep 41 through 42 until j˂q

Step 41: Print b[i][j]

Step 42: j←j+1

Step 43: i←i+1

Step 44: Set i←0

Step 45: Repeat step 46 through 50 until i˂m

Step 46: Set j←0

Step 47: Repeat step 48 through 49 until j˂q

Step 48: Print c[i][j]


Step 49: j←j+1

Step 50: i←i+1

Step 51: Stop

Program:

#Matrix multiplication using numpy

from numpy import*

m,n=input('Order of the first matrix: ')

p,q=input('Order of the second matrix: ')

if n==p:

print 'Enter %d elements of the first matrix (row wise) '%(m*n)

a=array([input() for i in range (m*n)])

a=a.reshape(m,n)

a=mat(a)

print 'Enter %d elements of the second matrix (row wise) '%(p*q)

b=array([input() for i in range (p*q)])

b=b.reshape(p,q)

b=mat(b)

c=a*b

print ' First matrix: \n',a

print ' Second matrix: \n',b

print 'Product of the matrices: \n',c

else:

print 'Matrix multiplication addition is not possible'


Result:

Order of the first matrix: 2,2

Order of the second matrix: 2,1

Enter 4 elements of the first matrix (row wise)

Enter 2 elements of the second matrix (row wise)

First matrix:

[[3 2]

[1 1]]

Second matrix:

[[1]

[2]]

Product of the matrices:

[[7]

[3]]
iv. Matrix multiplication without numpy

Algorithm:

Step 1: Enter the order of the first matrix

Step 2: Enter the order of the second matrix

Step 3: If n=p

Step 4: Enter the elements of the first matrix

Step 5: Enter the elements of the second matrix

Step 6: Do matrix multiplication

Step 7: Print result

Step 8: Stop

Program:

#Matrix multiplication without numpy

m,n=input('Order of the first matrix: ')

p,q=input('Order of the second matrix: ')

if n==p:

a=[]

print 'Enter %d elements of first matrix one by one (row wise)'%(m*n)

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)

print '\n\t First matrix: \n'

for i in range(m):

for j in range(n):

print '\t',a[i][j],

print

print '\n\t Second matrix: \n'

for i in range(p):

for j in range(q):
print '\t',b[i][j],

print

print '\n\t Product of matrices: \n'

for i in range(m):

for j in range(q):

print '\t',c[i][j],

print

else:

print 'Not compatible for matrix multiplication'

Result:

Order of the first matrix: 2,1

Order of the second matrix: 1,2

Enter 2 elements of first matrix one by one (row wise)

Enter 2 elements of second matrix one by one (row wise)

First matrix:

2
Second matrix:

3 4

Product of matrices:

3 4

6 8

v. Inverse of a matrix

Aim:

To find the inverse of a matrix.

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 1: Enter order o the matrix.

Step 2: If m≠n, go to step 7

Step 3: Enter elements of the matrix


Step 4: If determinant of the matrix is zero, print matrix is singulr and go to step 7

Step 5: Find the inverse of the matrix

Step 6: Print matrix has no trace and inverse

Step 7: Stop

Program:

#Inverse of matrix

from numpy import *

m,n=input('Order of the matrix: ')

if m==n:

print 'Enter the %d elements of the matrix (row wise):'%(m*m)

a=array([input() for i in range(m*m)])

a=a.reshape(m,m)

a=mat(a)

if linalg.det(a)==0:

print 'Matrix is singular'

else:

print 'Matrix: \n',a

c=a.I

print 'Inverse of the matrix: \n ',c

else:

print 'Matrix has no inverse'

Result:

Order of the matrix: 3,3


Enter the 9 elements of the matrix (row wise):

Matrix:

[[1 2 3]

[4 5 6]

[7 8 9]]

Inverse of the matrix:

[[ -4.50359963e+15 9.00719925e+15 -4.50359963e+15]

[ 9.00719925e+15 -1.80143985e+16 9.00719925e+15]

[ -4.50359963e+15 9.00719925e+15 -4.50359963e+15]]


Transpose of a Matrix

Aim:

To find the transpose of a matrix.

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.,

𝑎11 𝑎12 ⋯ 𝑎1𝑛


𝑎21 𝑎22 ⋯ 𝑎2𝑛
A=[ … … … … ]
… … … …
𝑎𝑚1 𝑎𝑚2 … 𝑎𝑚𝑛 𝑚×𝑛

𝑎11 𝑎21 ⋯ 𝑎𝑚1


𝑎12 𝑎22 ⋯ 𝑎𝑚2
AT = ⋯ ⋯ ⋯ ⋯
⋯ ⋯ ⋯ ⋯
[𝑎1𝑛 𝑎2𝑛 ⋯ 𝑎𝑚𝑛 ]𝑛×𝑚

or A = [aij]mxn and AT = [aji]nxm.

vi. Transpose of matrix using numpy

Algorithm:

Step 1: Enter rows and columns of matrix

Step 2: Enter the elements

Step 3: Print transpose of the matrix

Step 4: Stop

Program:
#Transpose of matrix using numpy

from numpy import *

m,n=input('Enter the order of the matrix: ')

print 'Enter %d elements of the matrix (row wise): '%(m*n)

a=array([input() for i in range(m*n)])

a=a.reshape(m,n)

a=mat(a)

b=a.T

print 'The original matrix: \n',a

print 'Transpose matrix: \n',b

Result:

Enter the order of the matrix: 3,3

Enter 9 elements of the matrix (row wise):

21

35

63

45

98

75

62

98

41

The original matrix:


[[21 35 63]

[45 98 75]

[62 98 41]]

Transpose matrix:

[[21 45 62]

[35 98 98]

[63 75 41]]

vii. Transpose of a matrix without numpy

Algorithm:

Step 1: Enter the order of the matrix (m,n)

Step 2: j←0 ; i←0

Step 3: If i˂m, then go to step 4, else go to step 8

Step 4: If j˂n, then go to step 5, else go to step 7

Step 5: Enter the element a[i][j]

Step 6: j←j+1; go to step 4

Step 7: i←i+1; j←0; go to step 3

Step 8: j←0; i←0

Step 9: If i˂m, then go to step 10, else go to step 12

Step 10: If j˂n, then go to step 11, else go to step 13

Step 11: Print a[j][i]

Step 12: j←j+1; go to step 10

Step 13: i←i+1; j←0; go to step 9

Step 14: Stop


Program:

#Transpose of a matrix without numpy

m,n=input('Enter order of the matrix: ')

a=[]

print 'Enter %d elements one by one (row wise): '%(m*n)

for i in range(m):

row=[]

for j in range(n):

row.append(input())

a.append(row)

print '\n\t The given matrix: \n'

for i in range(m):

for j in range(n):

print '\t',a[i][j],

print

print '\n\t The transpose matrix: \n'

for i in range(n):

for j in range(m):

print '\t',a[j][i],

print

Result:

Enter order of the matrix: 4,4

Enter 16 elements one by one (row wise):


1

11

13

14

15

The given matrix:

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:

To find the trace of a matrix.

Principle:

Sum of the diagonal elements of a square matrix is called its trace.

𝑎11 𝑎12 ⋯ 𝑎1𝑛


𝑎21 𝑎22 ⋯ 𝑎2𝑛
Let A = [ … … … … ]
… … … …
𝑎𝑛1 𝑎𝑛2 … 𝑎𝑛𝑛 𝑛×𝑛

Then trace of A is given by,

Tr(A)=𝑎11 + 𝑎22 + 𝑎33 + ⋯ + 𝑎𝑛𝑛 =∑𝑛𝑖=1 𝑎𝑖𝑖


viii. Trace of a matrix using numpy

Algorithm:

Step 1: Enter the order of a matrix m,n.

Step 2: If 𝑚 ≠ 𝑛, print matrix is not a square matrix and go to step 5

Step 3: Enter the matrix elements row wise and list in the matrix form.

Step 4: print the trace of the matrix.

Step 5: Stop.

Program:

from numpy import *

m,n=input(‘Enter the order of the matrix: ’)

if m==n:

print ‘Enter the %d elements of the matrix (row-wise):’%(m*m)

a=array([input() for I in range(m*m)])

a.reshape(m,n)

a=mat(a)

print ‘\n Given matrix: \n’,a

c=trace(a)

print ‘\nTrace of the matrix: \n’,c

else:

print ‘Not a sqaure matrix; trace not defined.’

Result:

Enter the order of the matrix: 3,3

Enter 9 elements of the matrix (row wise):


-15

-9

-5

-1.5

Given matrix:

[[-15. 4. -9. ]

[ 7. 6. -5. ]

[ 8. -1.5 7. ]]

Trace of the matrix:

-2.0

ix. Trace of a matrix without numpy

Algorithm:

Step 1: Enter the order of the matrix, m,n

Step 2: if 𝑚 ≠ 𝑛: print matrix is not a square matrix.


Step 3: i←0, j←0

Step 4: if i>n, go to step 9

Step 5: if j>n, go to step 8

Step 6: Enter element a[i][j]

Step 7: j←j+1, go to step 5

Step 8: i←i+1, go to step 4

Step 9: s←0

Step 10: i←0, j←0

Step 11: if i>n, go to step 16

Step 12: if j>n, go to step 15

Step 13: if i=j, s=s+a[i][j]

Step 14: j←j+1, go to step 12

Step 15: i←i+1, go to step 11

Step 16: print trace s.

Step 17: Stop.

Program:

#Trace of a matrix without numpy

m,n=input('Enter order of the matrix: ')

if m==n:

a=[]

print 'Enter %d elements one by one (row wise): '%(n*n)

for i in range(n):

b=[]
for j in range(n):

b.append(input())

a.append(b)

print '\n\t The given matrix: \n'

for i in range(n):

for j in range(n):

print '%4d'%a[i][j],

print

s=0

for i in range(n):

for j in range(n):

if i==j:

s=s+a[i][j]

print '\n Trace of above matrix',s

else:

print 'Not a square matrix'

Result:

Enter order of the matrix: 3,3

Enter 9 elements one by one (row wise):

-4

-8

5
21

-7

51

41

-8

The given matrix:

7 -4 -8

5 21 -7

51 41 -8

Trace of above matrix 20


x. Solutions of given set of non-homogenous equations using matrix

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 3: Solve the equations: linalg.solve(p,q)

Step 4: Print the solutions.

Step 5: End.

Program:

#Solution of given set of non-homogenous equations

#a+b+c+d=4

#2a+4b+6c+8d=8

#a-3b+4c-5d=-2

#5a+2b-3c-d=5.4

from numpy import *

print 'Enter the coefficients(row wise): '

p=array([input() for i in range(16)])

p=p.reshape(4,4)

print 'Enter the values of constants one by one: '

q=array([input() for i in range(4)])

q=q.reshape(1,4)

x=linalg.solve(p,q)

print 'Solutions are: \n'

print 'a=',x[0],'\nb=',x[1],'\nc=',x[2],'\nd=',x[3]
Result:

Enter the coefficients(row wise):

-3

-5

-3

-1

Enter the values of constants one by one:

-2

5.4
Solutions are:

a= [-3.06666667 -6.13333333 1.53333333 -4.14 ]

b= [ 10.4 20.8 -5.2 14.04]

c= [ 2.4 4.8 -1.2 3.24]

d= [ -5.73333333 -11.46666667 2.86666667 -7.74 ]


Runge-Kutta Method

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

The parameters are,

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

We obtain the method of Gill,

1 1
𝛼0 = 𝛼1 = 2 𝛽0 = 𝜐1 = 2 𝛽1 = 𝛽2 = 𝜐2 = 0

𝛿2 = 𝛿1 = 1 𝑤1 = 𝑤4 = 1/6 𝑤2 = 𝑤3 = 2/6

Leads to fourth order Runge-Kutta formula

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 1: Define f(x)

Step 2: Read x,y,n,xf

Step 3: h←(xf-x)/n

Step 4: for I in range 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

Step 10: y←y+(𝑘1 + 2 ∗ (𝑘2 + 𝑘3 ) + 𝑘4 )/6

Step 11: print the value of y

Step 12: stop

Program:

#Solution of second order differential equation

#RK method

from math import *


def f(x,y):

return x*x-2*x

x,y,n=input('Enter initial values of x,y and no. of intervals: ')

xf=input('Enter x for which y is required: ')

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

print 'The values of y at %f=%f' %(x,y)

Result:

Enter initial values of x,y and no. of intervals: 1,5,100

Enter x for which y is required: 3

The values of y at 3.000000=5.666667


Newton-Raphson Method

Aim:

To get the solution of algebraic and Transeendental equation by Newton Raphson


method.

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!

Neglecting the second and higher order derivatives,

f(x0) + hf’(x0) = 0

−𝑓(𝑥0 )
∴h= 𝑓 ′ (𝑥0 )

𝑓(𝑥 )
A better approximation than x0 is therefore given by x1, where x1=x0-𝑓′ (𝑥0 )
0

Successive approximations are given by x2, x3.....xn+1

𝑓(𝑥 )
where xn+1 = xn- 𝑓′ (𝑥𝑛 ) which is the Newton Raphson formula.
𝑛

Algorithm:

Step 1: Define f(x) ← given function.

Step 2: f1(x)← f’(x)

Step 3: Read x
Step 4: While |𝑓(𝑥)| > 10-6

𝑓(𝑥)
Step 5: x ← x – 𝑓 (𝑥)
1

Step 6: Print ‘the solution is=x’

Step 7: Stop.

Program:

#Newton Raphson Method

def f(x):

return x**2-2*x-1

def f1(x):

return 2*x-2

x=input('enter the approximate root:')

x=float(x)

while abs(f(x))>0.000001:

x=x-f(x)/f1(x)

print 'the solution is',x

Result:

enter the approximate root:3

the solution is 2.41421356237

You might also like