6

以下代码显示了矩阵的奇异性问题,因为在 Pycharm 中工作我得到

raise LinAlgError("Singular matrix")
numpy.linalg.linalg.LinAlgError: Singular matrix 

我想问题是 K,但我无法确切理解如何:

from numpy import zeros
from numpy.linalg import linalg
import math

def getA(kappa):
    matrix = zeros((n, n), float)
    for i in range(n):
    for j in range(n):
            matrix[i][j] = 2*math.cos((2*math.pi/n)*(abs(j-i))*kappa)
    return matrix


def getF(csi, a):
    csiInv = linalg.inv(csi)
    valueF = csiInv * a * csiInv * a
    traceF = valueF.trace()
    return 0.5 * traceF


def getG(csi, f, a):
    csiInv = linalg.inv(csi)

    valueG = (csiInv * a * csiInv) / (2 * f)
    return valueG


def getE(g, k):
    KInv = linalg.inv(k)
    Ktrans = linalg.transpose(k)
    KtransInv = linalg.inv(Ktrans)
    e = KtransInv * g * KInv
    return e


file = open('transformed.txt', 'r')
n = 4
transformed = zeros(n)

for counter, line in enumerate(file):
    if counter == n:
        break
    transformed[counter] = float(line)

CSI = zeros((n, n))
for i in range(n):
    for j in range(n):
        CSI[i][j] = transformed[abs(i-j)]

A = getA(1)
F = getF(CSI, A)
G = getG(CSI, F, A)

K = zeros((n, n), float)
for j in range(n):
    K[0][j] = 0.0001

for i in range(1, n):
    for j in range(n):
        K[i][j] = ((3.0*70.0*70.0*0.3)/(2.0*300000.0*300000.0))*((j*(i-j))/i)*(1.0+(70.0/300000.0)*j)



E = getE(G, K)

print G
print K

有没有人有任何修复它的建议?谢谢

4

1 回答 1

7

对非常“接近”奇异的矩阵求逆通常会导致计算问题。一个快速的技巧是在反转之前向矩阵的对角线添加一个非常小的值。

def getE(g, k):
    m = 10^-6
    KInv = linalg.inv(k + numpy.eye(k.shape[1])*m)
    Ktrans = linalg.transpose(k)
    KtransInv = linalg.inv(Ktrans + + numpy.eye(Ktrans.shape[1])*m)
    e = KtransInv * g * KInv
    return e

我认为这对家庭作业来说已经足够了。但是,如果您想真正部署计算上稳健的东西,您应该寻找反相的替代方案。

2x2 矩阵的数值稳定逆矩阵

于 2015-02-01T23:49:06.007 回答