w3resource

NumPy: Get the lower-triangular L in the Cholesky decomposition of a given array

NumPy: Linear Algebra Exercise-16 with Solution

Write a NumPy program to get the lower-triangular L in the Cholesky decomposition of a given array.

Sample Solution:

Python Code :

# Importing the NumPy library
import numpy as np

# Create a 3x3 NumPy array 'a' with specified values and data type as int32
a = np.array([[4, 12, -16], [12, 37, -53], [-16, -53, 98]], dtype=np.int32)

# Display the original array 'a'
print("Original array:")
print(a)

# Compute the Cholesky decomposition of the array 'a' using np.linalg.cholesky()
# Cholesky decomposition calculates the lower-triangular matrix 'L'
L = np.linalg.cholesky(a)

# Display the lower-triangular matrix 'L' obtained from Cholesky decomposition
print("Lower-triangular L in the Cholesky decomposition of the said array:")
print(L) 

Sample Output:

Original array:
[[  4  12 -16]
 [ 12  37 -53]
 [-16 -53  98]]
Lower-triangular L in the Cholesky decomposition of the said array:
[[ 2.  0.  0.]
 [ 6.  1.  0.]
 [-8. -5.  3.]]

Explanation:

In the above code –

a = np.array([[4, 12, -16], [12, 37, -53], [-16, -53, 98]], dtype=np.int32): This line creates a 3x3 NumPy array a with the specified elements and int32 data type.

L = np.linalg.cholesky(a): This line computes the Cholesky decomposition of the matrix a. The Cholesky decomposition is a technique used to decompose a Hermitian, positive-definite matrix into the product of a lower triangular matrix and its conjugate transpose. In this case, since a is a real, symmetric, and positive-definite matrix, the Cholesky decomposition can be applied. The result is a lower triangular matrix L such that a = L * L.T, where L.T is the transpose of L.

Python-Numpy Code Editor:

Previous: Write a NumPy program compute the sum of the diagonal element of a given array.
Next: Write a NumPy program to get the qr factorization of a given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.