用LAPACK包装器估计Cython中LU分解的行列式

2024-10-01 17:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义了计算矩阵行列式的函数。但有时我会弄错方向。我从this answer为函数建模。在

from scipy.linalg.cython_lapack cimport dgetrf

cpdef double det_c(double[:, ::1] A, double[:, ::1] work, double[::1] ipiv):
    '''obtain determinant of float type square matrix A

    Notes
    -----
    As is, this function is not yet computing the sign of the determinant
    correctly, help!

    Parameters
    ----------
    A : memoryview (numpy array)
        n x n array to compute determinant of
    work : memoryview (numpy array)
        n x n array to use within function
    ipiv : memoryview (numpy array)
        length n vector use within function

    Returns
    -------
    detval : float
        determinant of matrix A
    '''

    cdef int n = A.shape[0], info
    work[...] = A

    dgetrf(&n, &n, &work[0,0], &n, &ipiv[0], &info)

    cdef double detval = 1.
    cdef int j

    for j in range(n):
        if j != ipiv[j]:
            detval = -detval*work[j, j]
        else:
            detval = detval*work[j, j]

    return detval

当我测试这个函数并将它与np.linalg.det进行比较时,有时我得到了错误的符号。在

^{pr2}$

其他时候,是正确的标志。在

>>> b = np.array([[1,2,3],[1,2,1],[5,6,1.]])
>>> np.linalg.det(b)
>>> -7.999999999999998
>>> det_c(a, np.zeros((3, 3)), np.zeros(3, dtype=np.int32))
>>> -8.0

Tags: of函数numpynpfunctionarrayworkdouble

热门问题