2015-04-25 45 views
1

我試圖採用365x365矩陣的逆。其中一些數值大到365 ** 365,因此它們被轉換爲長數字。我不知道linalg.matrix_power()函數是否可以處理長數字。我知道問題來自於此(因爲錯誤消息,並且因爲我的程序對於較小的矩陣工作得很好),但我不確定是否有解決方法。代碼需要爲NxN矩陣工作。逆矩陣(Numpy)int太大,無法轉換爲浮點數

這裏是我的代碼:

item=0 
for i in xlist: 
    xtotal.append(arrayit.arrayit(xlist[item],len(xlist))) 
    item=item+1 
print xtotal 
xinverted=numpy.linalg.matrix_power(xtotal,-1) 
coeff=numpy.dot(xinverted,ylist) 

arrayit.arrayit

def arrayit(number, length): 
    newarray=[] 
    import decimal 
    i=0 
    while i!=(length): 
     newarray.insert(0,decimal.Decimal(number**i)) 
     i=i+1 
    return newarray; 

該方案是X,Y從列表(x和y會的名單列表)座標,使功能。 謝謝!

+0

你可以使用'Decimal(365 ** 365)' –

+2

你能描述一下你的用例嗎?這些是驚人的巨大數字。 – user2357112

+1

我相當有信心,'numpy.linalg.matrix_power'(但是考慮使用'numpy.linalg.inv'代替!)只適用於可以適合'double'或'long double'的數字。我不認爲它專用於像'decimal.Decimal'這樣的一般對象。如果你可以通過一個常量來縮放你的整個矩陣,所以它是合理的,你應該有更多的運氣(它看起來不像你的情況,儘管...)。 – DavidW

回答

0

你可能會嘗試的一件事是圖書館mpmath,它可以做任何精確數字的簡單矩陣代數和其他這樣的問題。

需要注意幾個問題:它幾乎肯定會比使用numpy的速度較慢,並且,在Lutzl his answer to this question指出,這個問題很可能不會被數學很好的界定。另外,您需要在開始之前決定所需的精度。

一些簡單的例子代碼,

from mpmath import mp, matrix 

# set the precision - see http://mpmath.org/doc/current/basics.html#setting-the-precision 
mp.prec = 5000 # set it to something big at the cost of speed. 
    # Ideally you'd precalculate what you need. 
    # a quick trial with 100*100 showed that 5000 works and 500 fails 

# see the documentation at http://mpmath.org/doc/current/matrices.html 
# where xtotal is the output from arrayit 
my_matrix = matrix(xtotal) # I think this should work. If not you'll have to create it and copy 

# do the inverse 
xinverted = my_matrix**-1 
coeff = xinverted*matrix(ylist) 
# note that as lutlz pointed out you really want to use solve instead of calculating the inverse. 
# I think this is something like 
from mpmath import lu_solve 
coeff = lu_solve(my_matrix,matrix(ylist)) 

我懷疑你的真正的問題是與數學,而不是軟件,所以我懷疑這會工作飛馳很好地爲您,但它總是可以的!

+0

謝謝!實際上我已經將整個計算編碼在其中,只是numpy庫不支持。它已經過了一年半了,所以現在可能會有所不同。對不起,我正在睡覺的遲到迴應。 :d –

0

你有沒有聽說過拉格朗日或牛頓插值?這將避免整個VanderMonde矩陣的構造。但不是係數中潛在的大數字。


作爲一般觀察,您不需要逆矩陣。你不需要計算它。你想要的是解決一個線性方程組。

x = numpy.linalg.solve(A, b) 

解決了系統A*x=b


你(真的)可能要來查找龍效果。採用等間隔採樣點插值是日益病態的任務。有用的結果可以獲得一位數的度數,較大的度數傾向於給出非常振盪的多項式。


您可以經常使用多項式迴歸,即通過一些低度的最佳多項式近似您的數據集。