Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise a numpy.matrix to non-integer power?

The ** operator for numpy.matrix does not support non-integer power:

>>> m
 matrix([[ 1. ,  0. ],
    [ 0.5,  0.5]])

>>> m ** 2.5
TypeError: exponent must be an integer

What I want is

octave:14> [1 0; .5 .5] ^ 2.5
ans =

   1.00000   0.00000
   0.82322   0.17678

Can I do this with numpy or scipy?

Note:

this is NOT an element-wise operation. It is an matrix (in linear algebra) raised to some power, as talked in this post.

like image 776
Frozen Flame Avatar asked Dec 22 '15 06:12

Frozen Flame


2 Answers

From this question you can see that the power of a matrix can be rewritten as: enter image description here.

This code, making use of scipy.linalg, gives as a result the same as Octave:

import numpy as np
from scipy.linalg import logm, expm

M = np.matrix([[ 1. ,  0. ],[ 0.5,  0.5]])
x = 2.5
A = logm(M)*x
P = expm(A)

This is the output for P:

Out[19]: 
array([[ 1.       , -0.       ],
   [ 0.8232233,  0.1767767]])
like image 127
charles Avatar answered Sep 20 '22 10:09

charles


You could use scipy.linalg.fractional_matrix_power:

>>> m
matrix([[ 1. ,  0. ],
        [ 0.5,  0.5]])
>>> scipy.linalg.fractional_matrix_power(m, 2.5)
array([[ 1.       ,  0.       ],
       [ 0.8232233,  0.1767767]])
like image 27
DSM Avatar answered Sep 22 '22 10:09

DSM