Mathematical Lab PDF
Mathematical Lab PDF
Mathematical Lab PDF
1. Python code for solving a system of linear equation using Gauss Elimination
Method
defgauss(A):
m =len(A)
assertall([len(row) == m +1for row inA[1:]]), "Matrix rows have non-uniform
length"
n = m +1
for kinrange(m):
pivots = [abs(A[i][k]) foriinrange(k, m)]
i_max=pivots.index(max(pivots)) + k
# Check for singular matrix
assertA[i_max][k] !=0, "Matrix is singular!"
# Swap rows
A[k], A[i_max] =A[i_max], A[k]
1.Generate a MATLAB code for solving a system of linear equation using Gauss
Elimination method.
% Matlab Program to solve (nxn) system equation
% by using Gaussian Elimination method
clear ; clc ; close all
n = input('Please Enter the size of the equation system n = ') ;
C = input('Please Enter the elements of the Matrix C ' ) ;
b = input('Please Enter the elements of the Matrix b ' ) ;
dett = det(C)
if dett == 0
print('This system unsolvable because det(C) = 0 ')
else
b = b'
A=[C b]
for j = 1:(n-1)
for i= (j+1) : n
mult = A(i,j)/A(j,j) ;
for k= j:n+1
A(i,k) = A(i,k) - mult*A(j,k) ;
A
end
end
end
for p = n:-1:1
for r = p+1:n
x(p) = A(p,r)/A(p,r-1)
end
end
end
Problem:
x1 + 2x2 - x3 = 3
2x1 + x2 - 2x3 = 3
-3x1 + x2 + x3 = -6
C = [ 1 2 -1 ; 2 1 -2 ; -3 1 1 ]
b= [ 3 3 -6 ]
Output:
Please Enter the size of the equation system n = 3
Please Enter the elements of the Matrix C [ 1 2 -1 ; 2 1 -2 ; -3 1 1 ]
Please Enter the elements of the Matrix b [ 3 3 -6 ]
dett =
6.0000
b=
3
3
-6
A=
1 2 -1 3
2 1 -2 3
-3 1 1 -6
A=
1 2 -1 3
0 1 -2 3
-3 1 1 -6
A=
1 2 -1 3
0 -3 -2 3
-3 1 1 -6
A=
1 2 -1 3
0 -3 0 3
-3 1 1 -6
A=
1 2 -1 3
0 -3 0 -3
-3 1 1 -6
A=
1 2 -1 3
0 -3 0 -3
0 1 1 -6
A=
1 2 -1 3
0 -3 0 -3
0 7 1 -6
A=
1 2 -1 3
0 -3 0 -3
0 7 -2 -6
A=
1 2 -1 3
0 -3 0 -3
0 7 -2 3
A=
1 2 -1 3
0 -3 0 -3
0 0 -2 3
A=
1 2 -1 3
0 -3 0 -3
0 0 -2 3
A=
1 2 -1 3
0 -3 0 -3
0 0 -2 -4
defmult_matrix(M, N):
"""Multiply square matrices of same dimension M and N"""
defpivot_matrix(M):
"""Returns the pivoting matrix for M, used in Doolittle's method."""
m =len(M)
returnid_mat
deflu_decomposition(A):
"""Performs an LU Decomposition of A (which must be square)
into PA = LU. The function returns P, L and U."""
n =len(A)
return(P, L, U)
A =[[7,3,-1,2],[3,8,1,-4],[-1,1,4,-1],[2,-4,-1,6]]
P, L, U =lu_decomposition(A)
print"A:"
pprint.pprint(A)
print"P:"
pprint.pprint(P)
print"L:"
pprint.pprint(L)
print"U:"
pprint.pprint(U)
The output from the pure Python implementation is given below:
A:
[[7, 3, -1, 2], [3, 8, 1, -4], [-1, 1, 4, -1], [2, -4, -1, 6]]
P:
[[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0]]
L:
[[1.0, 0.0, 0.0, 0.0],
[0.42857142857142855, 1.0, 0.0, 0.0],
[-0.14285714285714285, 0.2127659574468085, 1.0, 0.0],
[0.2857142857142857, -0.7234042553191489, 0.0898203592814371,
1.0]]
U:
[[7.0, 3.0, -1.0, 2.0],
[0.0, 6.714285714285714, 1.4285714285714286, -
4.857142857142857],
[0.0, 0.0, 3.5531914893617023, 0.31914893617021267],
[0.0, 0.0, 0.0, 1.88622754491018]]
None
0 0 1.0000 3.0000
0 0 0 1.0000
Lower =
1.0000 0 0 0
2.0000 -5.0000 0 0
Y=
1.0000
0.2000
Y=
1.0000
0.2000
6.0000
Y=
1.0000
0.2000
6.0000
1.5000
Y=
1.0000
0.2000
6.0000
1.5000
3.Python code for Iterative methods to solve equations using Jacobi Iteration.
def jacobi(A,b,N=25,x=None):
if x is None:
x = zeros(len(A[0]))
D = diag(A)
R = A - diagflat(D)
for i in range(N):
x = (b - dot(R,x)) / D
return x
A = array([[2.0,1.0],[5.0,7.0]])
b = array([11.0,13.0])
guess = array([1.0,1.0])
sol = jacobi(A,b,N=25,x=guess)
print "A:"
pprint(A)
print "b:"
pprint(b)
print "x:"
pprint(sol)
Output:
A:
[ 5., 7.]])
b:
x:
3. Generate a MATLAB code for Iterative methods to solve equations using Jacobi
Iteration
Program:
clc;clear all;close all
syms x y z
jacobian([x*y*z, y^2, x + z], [x, y, z])
Output:
[ y*z, x*z, x*y]
[ 0, 2*y, 0]
[ 1, 0, 1]
%first column output is differentiate with respect to x
%second column output is differentiate with respect to y
%third column output is differentiate with respect to z
return a * np.sin(b * x)
print(param)
print("Covariance of coefficients:")
print(param_cov)
ans = (param[0]*(np.sin(param[1]*x)))
# plt.legend()
# plt.show()
Output:
Program 1:
% cdate is a column vector containing the years 1790 to 1990 in 10-year
increments.
% pop is a column vector with the U.S. population figures that correspond to
the years in cdate .
plot( cdate, pop, 'o' )
[population2, gof] = fit( cdate, pop, 'poly2' );
figure
plot( population2, cdate, pop );
% Move the legend to the top left corner.
legend( 'Location', 'NorthWest' );
Output:
Figure: Plotting Data
# function to be solved
deff(x,y):
returnx+y
# or
# f = lambda x: x+y
# Euler method
defeuler(x0,y0,xn,n):
print('\n-----------SOLUTION-----------')
print('------------------------------')
print('x0\ty0\tslope\tyn')
print('------------------------------')
foriinrange(n):
slope =f(x0, y0)
yn= y0 + h * slope
print('%.4f\t%.4f\t%0.4f\t%.4f'%(x0,y0,slope,yn))
print('------------------------------')
y0 =yn
x0 = x0+h
# Inputs
print('Enter initial conditions:')
x0 =float(input('x0 = '))
y0 =float(input('y0 = '))
Output
Enter initial conditions:
x0 = 0
y0 = 1
Enter calculation point:
xn = 1
Enter number of steps:
Number of steps = 10
-----------SOLUTION-----------
------------------------------
x0 y0 slope yn
------------------------------
0.0000 1.0000 1.0000 1.1000
------------------------------
0.1000 1.1000 1.2000 1.2200
------------------------------
0.2000 1.2200 1.4200 1.3620
------------------------------
0.3000 1.3620 1.6620 1.5282
------------------------------
0.4000 1.5282 1.9282 1.7210
------------------------------
0.5000 1.7210 2.2210 1.9431
------------------------------
0.6000 1.9431 2.5431 2.1974
------------------------------
0.7000 2.1974 2.8974 2.4872
------------------------------
0.8000 2.4872 3.2872 2.8159
------------------------------
0.9000 2.8159 3.7159 3.1875
------------------------------
At x=1.0000, y=3.1875
Output:
2*n*x*euler(n - 1, x^2)
# function to be solved
deff(x,y):
returnx+y
# or
# f = lambda x: x+y
# RK-4 method
defrk4(x0,y0,xn,n):
print('\n--------SOLUTION--------')
print('-------------------------')
print('x0\ty0\tyn')
print('-------------------------')
foriinrange(n):
k1 = h *(f(x0, y0))
k2 = h *(f((x0+h/2),(y0+k1/2)))
k3 = h *(f((x0+h/2),(y0+k2/2)))
k4 = h *(f((x0+h),(y0+k3)))
k =(k1+2*k2+2*k3+k4)/6
yn= y0 + k
print('%.4f\t%.4f\t%.4f'%(x0,y0,yn))
print('-------------------------')
y0 =yn
x0 = x0+h
# Inputs
print('Enter initial conditions:')
x0 =float(input('x0 = '))
y0 =float(input('y0 = '))
Output
--------SOLUTION--------
-------------------------
x0 y0 yn
-------------------------
0.0000 1.0000 1.7969
-------------------------
0.5000 1.7969 3.4347
-------------------------
At x=1.0000, y=3.4347
Output:
8 Python code for Matrices and Eigen values i. Eigen values and Eigen vectors ii. Jacobi
method
from numpy.linalg import eig
import numpy as np
a=np.array([[10,20,30,40],[1,2,3,5],[7,8,9,10],[15,25,35,45]])
print(values)
print(vectors)
Output 1:
Eigen Values
Eigen Vectors
ii.import numpy as np
v = np.zeros ( [ n, n ] )
d = np.zeros ( n )
for j in range ( 0, n ):
for i in range ( 0, n ):
v[i,j] = 0.0
v[j,j] = 1.0
for i in range ( 0, n ):
d[i] = a[i,i]
bw = np.zeros ( n )
zw = np.zeros ( n )
w = np.zeros ( n )
for i in range ( 0, n ):
bw[i] = d[i]
it_num = 0
rot_num = 0
while ( it_num<it_max ):
it_num = it_num + 1
#
# The convergence threshold is based on the size of the elements in
# the strict upper triangle of the matrix.
#
thresh = 0.0
for j in range ( 0, n ):
for i in range ( 0, j ):
thresh = thresh + a[i,j] ** 2
if ( thresh == 0.0 ):
break
for p in range ( 0, n ):
for q in range ( p + 1, n ):
a[p,q] = 0.0
#
# Otherwise, apply a rotation.
#
elif( thresh<= abs ( a[p,q] ) ):
h = d[q] - d[p]
term = abs ( h ) + gapq
if ( term == abs ( h ) ):
t = a[p,q] / h
else:
theta = 0.5 * h / a[p,q]
t = 1.0 / ( abs ( theta ) + np.sqrt ( 1.0 + theta * theta ) )
if ( theta< 0.0 ):
t = - t
a[p,q] = 0.0
#
# Rotate, using information from the upper triangle of A only.
#
for j in range ( 0, p ):
g = a[j,p]
h = a[j,q]
a[j,p] = g - s * ( h + g * tau )
a[j,q] = h + s * ( g - h * tau )
for j in range ( p + 1, q ):
g = a[p,j]
h = a[j,q]
a[p,j] = g - s * ( h + g * tau )
a[j,q] = h + s * ( g - h * tau )
for j in range ( q + 1, n ):
g = a[p,j]
h = a[q,j]
a[p,j] = g - s * ( h + g * tau )
a[q,j] = h + s * ( g - h * tau )
#
# Accumulate information in the eigenvector matrix.
#
for j in range ( 0, n ):
g = v[j,p]
h = v[j,q]
v[j,p] = g - s * ( h + g * tau )
v[j,q] = h + s * ( g - h * tau )
rot_num = rot_num + 1
for i in range ( 0, n ):
bw[i] = bw[i] + zw[i]
d[i] = bw[i]
zw[i] = 0.0
#
# Restore upper triangle of input matrix.
#
for j in range ( 0, n ):
for i in range ( 0, j ):
a[i,j] = a[j,i]
#
# Ascending sort the eigenvalues and eigenvectors.
#
for k in range ( 0, n - 1 ):
m = k
for l in range ( k + 1, n ):
if ( d[l] < d[m] ):
m = l
if ( k != m ):
t = d[m]
d[m] = d[k]
d[k] = t
for i in range ( 0, n ):
w[i] = v[i,m]
v[i,m] = v[i,k]
v[i,k] = w[i]
def jacobi_eigenvalue_test01 ( ):
#****************************************************************************
*80
#
## JACOBI_EIGENVALUE_TEST01 uses a 4x4 test matrix.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 25 September 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
n = 4
a = np.array ( [ \
[ 4.0, -30.0, 60.0, -35.0, ], \
[ -30.0, 300.0, -675.0, 420.0, ], \
[ 60.0, -675.0, 1620.0, -1050.0, ], \
[ -35.0, 420.0, -1050.0, 700.0 ] ] )
print ( '' )
print ( 'JACOBI_EIGENVALUE_TEST01' )
print ( ' Python version: %s' % ( platform.python_version ( ) ) )
print ( ' JACOBI_EIGENVALUE computes the eigenvalues D' )
print ( ' and eigenvectors V of a symmetric matrix A so that A * V = D *
V.' )
it_max = 100
print ( '' )
print ( ' Number of iterations = %d' % ( it_num ) )
print ( ' Number of rotations = %d' % ( rot_num ) )
def jacobi_eigenvalue_test02 ( ):
Output:
JACOBI_EIGENVALUE_TEST
Python version: 3.6.5
Test the JACOBI_EIGENVALUE library.
JACOBI_EIGENVALUE_TEST01
Python version: 3.6.5
JACOBI_EIGENVALUE computes the eigenvalues D
and eigenvectors V of a symmetric matrix A so that A * V = D * V.
Input matrix A:
Col: 0 1 2 3
Row
0 : 4 -30 60 -35
1 : -30 300 -675 420
2 : 60 -675 1620 -1050
3 : -35 420 -1050 700
Number of iterations = 11
Number of rotations = 21
Eigenvalues D:
0: 0.166643
1: 1.47805
2: 37.1015
3: 2585.25
Eigenvector matrix V:
Col: 0 1 2 3
Row
0 : 0.792608 0.582076 0.179186 0.0291933
1 : 0.451923 -0.370502 -0.741918 -0.328712
2 : 0.322416 -0.509579 0.100228 0.791411
3 : 0.252161 -0.514048 0.638283 -0.514553
JACOBI_EIGENVALUE_TEST01
Normal end of execution.
V=
-0.2320 -0.7858 0.4082
-0.5253 -0.0868 -0.8165
-0.8187 0.6123 0.408
D=
16.1168 0 0
0 -1.1168 0
0 0 -0.0000
W=
-0.4645 -0.8829 0.4082
-0.5708 -0.2395 -0.8165
-0.6770 0.4039 0.4082
sol = pdepe(m,@pdex1pde,@pdex1ic,@pdex1bc,x,t);
% pdepe is command for Partial DE
% Extract the first solution component as u.
u = sol(:,:,1);
Output: