In Python, How Can I Raise A Square Matrix Represented As A Numpy.ndarray To Non-integer Powers?
Solution 1:
SciPy has scipy.linalg.sqrtm
, which computes a matrix square root. It's not clear whether it attempts to compute any particular square root - for example, the principal square root - but if the input has square roots, sqrtm
will compute one. Thus, you can do
invsqrt = scipy.linalg.sqrtm(scipy.linalg.inv(input_matrix))
though you'll likely want to do some error-handling.
Solution 2:
There is no guarantee that a general n x n matrix can be raised to a given non-integer power. This operation is well-defined for positive integer powers, and using Maclaurin series you can then define a matrix exponential function for approximating other functions of matrices.
However, to be able to raise a matrix to an arbitrary power, you must also have a coherent definition of a matrix logarithm, which is only well-defined for invertible matrices and involves some subtlety about uniqueness and the field of elements over which it is defined.
This is covered reasonably well at this math.stackexchange.com answer.
So in general, this is not a well-defined operation on arbitrary n x n matrices, and thus it wouldn't make sense as a generically available function on ndarray
.
It's like asking for a function called "inverse
" that calculates an inverse (not a psuedo-inverse or any approximation, but the "actual" inverse) for arbitrary 2D arrays. Such a function can't exist in general, since there are non-invertible 2D arrays.
It's somewhat of a parochial API decision as to whether there is some function that purports to compute it and merely throws an exception if it can detect an invalid input argument, such as numpy.linalg.inv
, versus just not providing that functionality and expecting the user to write their own function to do it and to handle checking argument validity, raising exceptions, or whatever failure-case behavior is required.
inv
is ubiquitous enough to warrant this effort, whereas out-of-the-box arbitrary powers are not.
Post a Comment for "In Python, How Can I Raise A Square Matrix Represented As A Numpy.ndarray To Non-integer Powers?"