Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use numpy.linalg.matrix_power in python to raise a matrix to a large power?

I am trying to raise a matrix to a high power in python/numpy. It seems that for large exponents, the results are not correct(some sort of overflow?), above 10000. Is this a known behavior of the numpy.linalg.matrix_power function or am I missing something? Here is the code I am trying with its output:

import numpy as np
from numpy import linalg as LA
A = np.array([1L,1L,1L,0L]).reshape(2,2)
print 'A: %s'%A
print 'A^10: %s'%LA.matrix_power(A,10)
print 'A^1000: %s'%LA.matrix_power(A,1000)
print 'A^10000: %s'%LA.matrix_power(A,10000)

Output:

A: 
[[1 1]
 [1 0]]
A^10: 
[[89 55]
 [55 34]]
A^1000: 
[[9079565065540428013 817770325994397771]
 [817770325994397771 8261794739546030242]]
A^10000: 
[[-83367563645688771 -2872092127636481573]
 [-2872092127636481573 2788724563990792802]]
like image 501
farmi Avatar asked Dec 14 '25 13:12

farmi


1 Answers

You've exceeded the maximum value representable in a 64-bit integer. You can try this instead:

A = np.array([1L,1L,1L,0L], dtype=float).reshape(2,2)

But note when you raise A to the 10000th power, it will give you infinity. At least that's better than negative numbers.

If you really need this math to be done, you may have to use multiple-precision arithmetic instead (see Jaime's excellent comment below).

like image 85
John Zwinck Avatar answered Dec 17 '25 09:12

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!