Created
October 13, 2015 12:22
-
-
Save east825/cce6f1e2eb1e9c8481ad to your computer and use it in GitHub Desktop.
Numpy docstring with arcane formatting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def cond(x, p=None): | |
""" | |
Compute the condition number of a matrix. | |
This function is capable of returning the condition number using | |
one of seven different norms, depending on the value of `p` (see | |
Parameters below). | |
Parameters | |
---------- | |
x : (M, N) array_like | |
The matrix whose condition number is sought. | |
p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional | |
Order of the norm: | |
===== ============================ | |
p norm for matrices | |
===== ============================ | |
None 2-norm, computed directly using the ``SVD`` | |
'fro' Frobenius norm | |
inf max(sum(abs(x), axis=1)) | |
-inf min(sum(abs(x), axis=1)) | |
1 max(sum(abs(x), axis=0)) | |
-1 min(sum(abs(x), axis=0)) | |
2 2-norm (largest sing. value) | |
-2 smallest singular value | |
===== ============================ | |
inf means the numpy.inf object, and the Frobenius norm is | |
the root-of-sum-of-squares norm. | |
Returns | |
------- | |
c : {float, inf} | |
The condition number of the matrix. May be infinite. | |
See Also | |
-------- | |
numpy.linalg.norm | |
Notes | |
----- | |
The condition number of `x` is defined as the norm of `x` times the | |
norm of the inverse of `x` [1]_; the norm can be the usual L2-norm | |
(root-of-sum-of-squares) or one of a number of other matrix norms. | |
References | |
---------- | |
.. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL, | |
Academic Press, Inc., 1980, pg. 285. | |
Examples | |
-------- | |
>>> from numpy import linalg as LA | |
>>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]]) | |
>>> a | |
array([[ 1, 0, -1], | |
[ 0, 1, 0], | |
[ 1, 0, 1]]) | |
>>> LA.cond(a) | |
1.4142135623730951 | |
>>> LA.cond(a, 'fro') | |
3.1622776601683795 | |
>>> LA.cond(a, np.inf) | |
2.0 | |
>>> LA.cond(a, -np.inf) | |
1.0 | |
>>> LA.cond(a, 1) | |
2.0 | |
>>> LA.cond(a, -1) | |
1.0 | |
>>> LA.cond(a, 2) | |
1.4142135623730951 | |
>>> LA.cond(a, -2) | |
0.70710678118654746 | |
>>> min(LA.svd(a, compute_uv=0))*min(LA.svd(LA.inv(a), compute_uv=0)) | |
0.70710678118654746 | |
""" | |
x = asarray(x) # in case we have a matrix | |
if p is None: | |
s = svd(x, compute_uv=False) | |
return s[0]/s[-1] | |
else: | |
return norm(x, p)*norm(inv(x), p) | |
a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]]) | |
cond(a, "fro") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment