Fifth
Fifth
md 2024-11-10
Assignment 5
Question 1
import numpy as np
A=np.array([[8,6,2,3],[3,8,4,3],[5,2,6,8],[9,2,3,4]],dtype=float)
B=np.array([20,24,12,14],dtype=float)
print("Solution X:", X)
This code uses Gaussian elimination followed by back-substitution to solve a system of linear equations (
AX = B ).
. Gaussian Elimination: It iterates through each column, eliminating elements below the main diagonal
to transform matrix ( A ) into an upper triangular form. For each row ( j ) below row ( i ), it calculates a
factor, then updates A[j] and B[j] to zero out the entries below the diagonal.
Question 2
import numpy as np
1/7
Fifth.md 2024-11-10
A = np.array([[8,6,2,3],[3,8,4,3],[5,2,6,8],[9,2,3,4]], dtype=float)
B = np.array([20,24,12,14], dtype=float)
def lu_decomposition(A):
n = len(A)
L = np.zeros((n, n))
U = np.zeros((n, n))
for i in range(n):
# Set diagonal elements of L to 1
L[i][i] = 1
# Compute U
for j in range(i, n):
s1 = sum(U[k][j] * L[i][k] for k in range(i))
U[i][j] = A[i][j] - s1
# Compute L
for j in range(i + 1, n):
s2 = sum(U[k][i] * L[j][k] for k in range(i))
L[j][i] = (A[j][i] - s2) / U[i][i]
return L, U
return x
x = solve_linear_system(A, B)
print("Solution X:", x)
This code uses Doolittle's method to perform LU decomposition on matrix ( A ), decomposing it into a
lower triangular matrix ( L ) and an upper triangular matrix ( U ), where ( L ) has 1s along its diagonal.
In this method for LU decomposition decomposes a matrix ( A ) such that:
[ A = LU ]
Where:
2/7
Fifth.md 2024-11-10
def lu_decomposition(A):
n = len(A)
L = np.zeros((n, n))
U = np.zeros((n, n))
for i in range(n):
# Set diagonal elements of L to 1
L[i][i] = 1
Calculating ( U[i][j] ): For each row ( i ), we calculate the entries of ( U ) from column ( i ) to ( n ).
Sum Calculation ( s1 ): We compute the sum ( s1 ) of products from previous rows that
contribute to ( U[i][j] ), defined as:
[ s1 = \sum_{k=0}^{i-1} U[k][j] \cdot L[i][k] ]
Subtracting ( s1 ) from ( A[i][j] ): The final element of ( U[i][j] ) is calculated by subtracting
this sum from ( A[i][j] ):
[ U[i][j] = A[i][j] - s1 ]
This part of the code handles all entries of ( U ) in the current row.
3. Filling in the Elements of ( L ) (Lower Triangular Matrix)
3/7
Fifth.md 2024-11-10
singular!")
L[j][i] = (A[j][i] - s2) / U[i][i]
Calculating ( L[j][i] ): For each column ( i ), we calculate the entries of ( L ) below the diagonal (from
row ( i+1 ) to ( n )).
Sum Calculation ( s2 ): We compute the sum ( s2 ) of products from previous columns that
contribute to ( L[j][i] ):
[ s2 = \sum_{k=0}^{i-1} U[k][i] \cdot L[j][k] ]
Subtracting ( s2 ) and Dividing by ( U[i][i] ): The final element of ( L[j][i] ) is calculated by
subtracting this sum from ( A[j][i] ) and dividing by ( U[i][i] ):
[ L[j][i] = \frac{A[j][i] - s2}{U[i][i]} ]
This part of the code fills in all entries of ( L ) in the current column below the diagonal.
4. Solving the System Using Forward and Back Substitution
After the decomposition, we solve the system ( AX = B ) in two steps using forward and back substitution.
Forward Substitution (( Ly = B ))
y = np.zeros_like(b)
for i in range(len(y)):
temp_sum = sum(L[i][j] * y[j] for j in range(i))
y[i] = (b[i] - temp_sum) / L[i][i]
Solving ( Ly = B ): Since ( L ) is a lower triangular matrix, we can solve for ( y ) by iterating from the
top row downwards, using previously calculated values of ( y ) to find the next value.
Back Substitution (( Ux = y ))
x = np.zeros_like(y)
for i in range(len(x) - 1, -1, -1):
temp_sum = sum(U[i][j] * x[j] for j in range(i + 1, len(x)))
x[i] = (y[i] - temp_sum) / U[i][i]
Solving ( Ux = y ): Since ( U ) is an upper triangular matrix, we can solve for ( x ) by iterating from the
bottom row upwards.
Output:
4/7
Fifth.md 2024-11-10
Question 3
import numpy as np
import matplotlib.pyplot as plt
import random
learning_rate = 0.0001 # Step size (smaller step size, more accurate but
slower convergence)
iterations = 1000 # Number of iterations (more iterations, more accurate,
but slower)
# Update m and b
m -= learning_rate * dm
b -= learning_rate * db
return m, b
print(f"X: {X}")
print(f"Y: {Y}")
print(f"Equation of the fitted line: y = {m:.2f}x + {b:.2f}")
plt.figure(figsize=(8, 6))
plt.scatter(X, Y, color="blue", label="Data Points")
plt.plot(X, m * X + b, color="red", label=f"Fitted Line: y = {m:.2f}x +
{b:.2f}")
plt.xlabel("X")
plt.ylabel("Y")
5/7
Fifth.md 2024-11-10
X: [64 23 70 54 80 13 32 58 21 60 65 78 43 63 62 21 73 77 88 42]
Y: [124 52 132 119 166 20 71 120 44 125 133 164 87 121 118 40 138
161169 88]
6/7
Fifth.md 2024-11-10
7/7