gpt4 book ai didi

python - 在 Cython 中使用 LAPACK 包装器估计行列式进行 LU 分解

转载 作者:太空宇宙 更新时间:2023-11-03 13:29:01 24 4
gpt4 key购买 nike

我在这里定义了计算矩阵行列式的函数。但有时我得到错误的标志。我从 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 进行比较时,有时我会得到错误的符号。

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

其他时候,正确的标志。

>>> 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

最佳答案

dgetrf 是 Fortran 子程序,Fortran 使用从 1 开始的索引,所以 ipiv 中的值在 1 到 n 之间(包括).为了解决这个问题,将循环中的测试从

        if j != ipiv[j]:

        if j != ipiv[j] - 1:

关于python - 在 Cython 中使用 LAPACK 包装器估计行列式进行 LU 分解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50284132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com