I needed to compute Q^N for quite a lot of various values of N (between 1 to 10000) and Numpy was a bit too slow.
I've asked on math.stackexchange.com if I could avoid to compute Q^N for my specific need and someone answered me that computing Q^N should be quite fast using the P D^N P^-1
method.
So basically, instead of doing:
import numpy as np
from numpy import linalg as LA
...
LA.matrix_power(m, N)
I've tried :
diag, P = LA.eig(m)
DN = np.diag(diag**N)
P1 = LA.inv(P)
P*DN*P1
And I obtain the same matrix as result (tried on a single example)
On a more complex matrix, Q:
% timeit.Timer('Q**10000', setup=setup).repeat(2, 100)
[5.87254786491394, 5.863131046295166]
% timeit.Timer('diag, P = linalg.eig(Q); DN=np.diag(diag**10000);P1=linalg.inv(P); P*DN*P1', setup=setup).repeat(2, 100)
[2.0032401084899902, 2.018735885620117]
And regarding my initial problem, the second method allows me to compute P, diag and P1
only once and use it thousands of times. It's 8 times faster using this method.
My questions are:
- In which case it is not possible to use this last method to compute Q^N?
- Is it fine to use it in my case (matrix Q as given here)?
- Is there in numpy a function that already does it?
Edit:
- It appears that for another matrix, P is not invertible. So I am adding a new question: how can I change the matrix P so it becomes invertible but the resulting matrix is not too altered? I mean, it's ok if the values are close to the real result, by close I mean ~0.0001.