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]]
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.