]> gitweb.michael.orlitzky.com - dunshire.git/commitdiff
Add the specnorm() function to the matrices module.
authorMichael Orlitzky <michael@orlitzky.com>
Fri, 11 Nov 2016 01:23:24 +0000 (20:23 -0500)
committerMichael Orlitzky <michael@orlitzky.com>
Sun, 13 Nov 2016 20:19:26 +0000 (15:19 -0500)
dunshire/matrices.py

index 123085c6c02f69574dc614fcff49d46207b7981c..a5a02e9d069eea87b2cf44cb70054133f3e4ae8c 100644 (file)
@@ -341,6 +341,42 @@ def norm(matrix_or_vector):
     return sqrt(inner_product(matrix_or_vector, matrix_or_vector))
 
 
+def specnorm(mat):
+    """
+    Return the spectral norm of a matrix.
+
+    The spectral norm of a matrix is its largest singular value, and it
+    corresponds to the operator norm induced by the vector ``2``-norm.
+
+    Parameters
+    ----------
+
+    mat : matrix
+        The matrix whose spectral norm you want.
+
+    Examples:
+
+        >>> specnorm(identity(3))
+        1.0
+
+        >>> specnorm(5*identity(4))
+        5.0
+
+    """
+    num_eigs = min(mat.size)
+    eigs = matrix(0, (num_eigs, 1), tc='d')
+    typecode = 'd'
+    if any([isinstance(entry, complex) for entry in mat]):
+        typecode = 'z'
+    dummy = matrix(mat, mat.size, tc=typecode)
+    gesdd(dummy, eigs)
+
+    if len(eigs) > 0:
+        return eigs[0]
+    else:
+        return 0
+
+
 def vec(mat):
     """
     Create a long vector in column-major order from ``mat``.