Skip to content
Related Articles

Related Articles

Improve Article

Compute the condition number of a given matrix using NumPy

  • Last Updated : 29 Aug, 2020

In this article, we will use the cond() function of the NumPy package to calculate the condition number of a given matrix. cond() is a function of linear algebra module in NumPy package.

Syntax: 

numpy.linalg.cond(x, p=None)

Example 1: Condition Number of 2X2 matrix

Python3




# Importing library
import numpy as np
  
# Creating a 2X2 matrix
matrix = np.array([[4, 2], [3, 1]])
  
print("Original matrix:")
print(matrix)
  
# Output
result =  np.linalg.cond(matrix)
  
print("Condition number of the matrix:")
print(result)

Output:



Original matrix:
[[4 2]
 [3 1]]
Condition number of the matrix:
14.933034373659256

Example 2: Condition Number of 3X3 matrix

Python3




# Importing library
import numpy as np
  
# Creating a 3X3 matrix
matrix = np.array([[4, 2, 0], [3, 1, 2], [1, 6, 4]])
  
print("Original matrix:")
print(matrix)
  
# Output
result =  np.linalg.cond(matrix)
  
print("Condition number of the matrix:")
print(result)

Output:

Original matrix:
[[4 2 0]
 [3 1 2]
 [1 6 4]]
Condition number of the matrix:
5.347703616656448

Example 3: Condition Number of 4X4 matrix

Python3




# Importing library
import numpy as np
  
# Creating a 4X4 matrix
matrix = np.array([[4, 1, 4, 2], [3, 1, 2, 0], 
                   [3, 5, 7 ,1], [0, 6, 8, 4]])
  
print("Original matrix:")
print(matrix)
  
# Output
result =  np.linalg.cond(matrix)
  
print("Condition number of the matrix:")
print(result)

Output:

Original matrix:
[[4 1 4 2]
 [3 1 2 0]
 [3 5 7 1]
 [0 6 8 4]]
Condition number of the matrix:
57.34043866386226

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :