0% found this document useful (0 votes)
9 views4 pages

Reyvill Code

numerical analysis

Uploaded by

Benji Mejos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views4 pages

Reyvill Code

numerical analysis

Uploaded by

Benji Mejos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Code:

import scipy.linalg as la
import numpy as np

# Define the coefficient matrix A and the constant vector b


A = np.array([[1, 3, -2],
[3, 1, 4],
[-2, 1, 2]])

b = np.array([-4, 4, 7])

# LU Decomposition (without pivoting)


P, L, U = la.lu(A)

print("Matrix L:\n", L)
print("Matrix U:\n", U)
print("Permutation Matrix P:\n", P)

# Solve LUx = Pb
Pb = np.dot(P, b)
y = la.solve_triangular(L, Pb, lower=True)
x = la.solve_triangular(U, y)
print("Solution of the system:", x)

# From problem 2, we already got P, L, and U


# Solve using PA = LU

# Already done in Problem 2 using scipy's lu()

# Reconfirming the solution:


Pb = np.dot(P, b)
y = la.solve_triangular(L, Pb, lower=True)
x = la.solve_triangular(U, y)

print("Solution using PA = LU:", x)

Output:

Matrix L:
[[ 1. 0. 0. ]

[ 0.33333333 1. 0. ]

[-0.66666667 0.625 1. ]]

Matrix U:

[[ 3. 1. 4. ]

[ 0. 2.66666667 -3.33333333]

[ 0. 0. 6.75 ]]

Permutation Matrix P:

[[0. 1. 0.]

[1. 0. 0.]

[0. 0. 1.]]

Solution of the system: [-1.37037037 0.40740741 1.92592593]

Solution using PA = LU: [-1.37037037 0.40740741 1.92592593]

Code:

import numpy as np
from scipy.linalg import lu, solve_triangular
# Define matrix A and vector b
A = np.array([[1, 3, -2],
[3, 1, 4],
[-2, 1, 2]], dtype=float)
b = np.array([-4, 4, 7], dtype=float)

# LU Decomposition with partial pivoting (PA = LU)


P, L, U = lu(A)

# Solve for Pb
Pb = np.dot(P, b)

# Forward substitution to solve Ly = Pb


y = solve_triangular(L, Pb, lower=True)

# Backward substitution to solve Ux = y


x = solve_triangular(U, y)

# Set display precision


np.set_printoptions(precision=8, suppress=True)

# Print results
print("Matrix L: (Lower Triangular)")
print(L)

print("\nMatrix U: (Upper Triangular)")


print(U)

print("\nPermutation Matrix P: (Permutation)")


print(P)

print("\nSolution x:")
print(x)

Output:

Matrix L: (Lower Triangular)

[[ 1. 0. 0. ]

[ 0.33333333 1. 0. ]
[-0.66666667 0.625 1. ]]

Matrix U: (Upper Triangular)

[[ 3. 1. 4. ]

[ 0. 2.66666667 -3.33333333]

[ 0. 0. 6.75 ]]

Permutation Matrix P: (Permutation)

[[0. 1. 0.]

[1. 0. 0.]

[0. 0. 1.]]

Solution x:

[-1.37037037 0.40740741 1.92592593]

You might also like