w3resource

Creating a 3x3 array and computing Cholesky Decomposition using NumPy

NumPy: Advanced Exercise-28 with Solution

Write a NumPy program to create a 3x3 array with random values and compute the Cholesky decomposition.

Cholesky decomposition is a method to decompose a symmetric positive definite matrix into the product of a lower triangular matrix and its transpose. This decomposition is often used in numerical simulations and optimization algorithms because it simplifies certain calculations. In NumPy, the function numpy.linalg.cholesky() computes the Cholesky decomposition.

Sample Solution:

Python Code:

import numpy as np

# Create a 3x3 array with random values
array = np.random.random((3, 3))

# Make the array symmetric and positive-definite for Cholesky decomposition
symmetric_array = np.dot(array, array.T)

# Compute the Cholesky decomposition
cholesky_decomp = np.linalg.cholesky(symmetric_array)

# Print the original array, symmetric array, and Cholesky decomposition
print("Original Array:\n", array)
print("Symmetric Positive-Definite Array:\n", symmetric_array)
print("Cholesky Decomposition:\n", cholesky_decomp)

Output:

Original Array:
 [[0.55421335 0.88003201 0.69341047]
 [0.16909153 0.06973867 0.50623688]
 [0.85878634 0.00377919 0.29339117]]
Symmetric Positive-Definite Array:
 [[1.56242685 0.506115   0.68271717]
 [0.506115   0.28973121 0.29400248]
 [0.68271717 0.29400248 0.82360665]]
Cholesky Decomposition:
 [[1.24997074 0.         0.        ]
 [0.40490148 0.35466322 0.        ]
 [0.54618652 0.20540825 0.69504991]]

Explanation:

  • Import NumPy: Import the NumPy library to work with arrays.
  • Create a Random 3x3 Array: Generate a 3x3 array filled with random values using np.random.random.
  • Make the Array Symmetric and Positive-Definite: Compute the dot product of the array with its transpose to ensure it is symmetric and positive-definite, which is a requirement for Cholesky decomposition.
  • Compute Cholesky Decomposition: Use np.linalg.cholesky to compute the Cholesky decomposition of the symmetric positive-definite array.
  • Print Results: Print the original array, the symmetric positive-definite array, and the result of the Cholesky decomposition.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Creating a 3x3 array and computing QR decomposition using NumPy.
Next: Swapping the first and last rows of a 4x4 array using NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/advanced-numpy-exercise-28.php