Creating a 3x3 array and computing Cholesky Decomposition using NumPy
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics