Tutorial5 and Quiz Solutions
Tutorial5 and Quiz Solutions
February 9, 2023
1 Tutorial 5
1.1 Learning Objectives
• Practice to solve linear systems using:
– Gauss elimination
– LU factorization
– Inverse matrix
• Solution to a tridiagonal matrix
• Newton Rapson for solving a non-linear system of equations
Use Gauss elimination, LU factorization and Inverse matrix to solve the system of equations.
# Create matrix A
A = np.matrix([[3.,-6.,12.],
[-1.,3.,-3.],
[4.,5.,6.]])
AOrg = A
1
[[3.]
[2.]
[1.]]
[43]: # LU factorize A
A = AOrg
b = bOrg
(L,U) = lnls.LUfactorization( A )
# Print L and U
print(f'L = {L}')
print(f'U = {U}')
L = [[ 1. 0. 0. ]
[-0.33333333 1. 0. ]
[ 1.33333333 13. 1. ]]
U = [[ 3. -6. 12.]
[ 0. 1. 1.]
[ 0. 0. -23.]]
Res = [[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[44]: y = lnls.GaussElimination(L, b)
x = lnls.GaussElimination(U, y)
print(x)
[[3.]
[2.]
[1.]]
[45]: x = lnls.LUsolve(L,U,b)
print(x)
[[3.]
[2.]
[1.]]
2
1.2.3 Solution using Matrix inverse
[28]: A = AOrg
b = bOrg
# Compute A^-1
Am1 = lnls.ComputeInvMat( A )
print('The inverse matrix is Am1=',Am1)
[29]: x = Am1.dot(b)
print(x)
[[3.]
[2.]
[1.]]
4 1 𝑥0 6
⎡ 2 4 1 ⎤⎡ 𝑥1 ⎤ ⎡ 13 ⎤
⎢ ⎥⎢ ⎥ ⎢ ⎥
⎢ 2 4 1 ⎥⎢ 𝑥2 ⎥=⎢ 18 ⎥
⎢ 2 4 1 ⎥⎢ 𝑥3 ⎥ ⎢ 15 ⎥
⎣ 2 4 ⎦⎣ 𝑥4 ⎦ ⎣ 8 ⎦
3
# Solve the system
x = lnls.Tridiag(e, f, g, b)
print('Solution is x =\n', x)
Solution is x =
[[1.]
[2.]
[3.]
[2.]
[1.]]
𝜕𝑓0 𝜕𝑓0
𝜕𝑥0 𝜕𝑥1
𝐽 =[ 𝜕𝑓1 𝜕𝑓1 ]
𝜕𝑥0 𝜕𝑥1
def func2by2( x ):
f = np.transpose([np.zeros(2)])
f[0] = f0( x[0], x[1] )
f[1] = f1( x[0], x[1] )
return f
4
def J2by2_approx( x, h ):
J = np.matrix(np.zeros((2,2)))
J[0,0] = ( f0( x[0]+h, x[1]) - f0( x[0]-h, x[1]) ) / ( 2 * h )
J[0,1] = ( f0( x[0], x[1]+h) - f0( x[0], x[1]-h) ) / ( 2 * h )
J[1,0] = ( f1( x[0]+h, x[1]) - f1( x[0]-h, x[1]) ) / ( 2 * h )
J[1,1] = ( f1( x[0], x[1]+h) - f1( x[0], x[1]-h) ) / ( 2 * h )
return J
def J2by2( x, h ):
J = np.zeros((2,2))
J[0,0] = 9 * x[0]**2 + 2 * x[1]**2
J[0,1] = 4 * x[0] * x[1]
J[1,0] = 2 * x[0]
J[1,1] = -11
return J
5
0 0 7.355825629 54.57464059
1 1 0.455100143 8.188828004
2 2 0.001841680065 0.4914992071
3 3 3.051266716e-08 0.001986858961
4 4 3.552713679e-15 3.28881674e-08
5 5 7.105427358e-15 1.426271926e-14
Solution is x =
[[2.]
[2.]]
def func2by2( x ):
f = np.transpose([np.zeros(2)])
f[0] = f0( x[0], x[1] )
f[1] = f1( x[0], x[1] )
return f
def J2by2_approx( x, h ):
J = np.matrix(np.zeros((2,2)))
J[0,0] = ( f0( x[0]+h, x[1]) - f0( x[0]-h, x[1]) ) / ( 2 * h )
J[0,1] = ( f0( x[0], x[1]+h) - f0( x[0], x[1]-h) ) / ( 2 * h )
J[1,0] = ( f1( x[0]+h, x[1]) - f1( x[0]-h, x[1]) ) / ( 2 * h )
J[1,1] = ( f1( x[0], x[1]+h) - f1( x[0], x[1]-h) ) / ( 2 * h )
return J
6
2 2 0.03798219849 9.837558337
3 3 0.001156450023 1.76961688
4 4 1.189320795e-06 0.05723708497
5 5 2.1599367e-12 5.899505248e-05
6 6 2.220446049e-16 1.079090944e-10
Solution is x =
[[0.9734681 ]
[1.53391362]]
[ ]: