2015-04-25 47 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


你(真的)可能要来查找龙效果。采用等间隔采样点插值是日益病态的任务。有用的结果可以获得一位数的度数,较大的度数倾向于给出非常振荡的多项式。


您可以经常使用多项式回归,即通过一些低度的最佳多项式近似您的数据集。