update
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
import numpy as np
|
||||
import example
|
||||
|
||||
A = [[1.0, 2.0, 3.0],
|
||||
[0.0, 1.0, 4.0],
|
||||
[5.0, 6.0, 0.0]]
|
||||
|
||||
Ainv_1 = np.asfortranarray(np.empty_like(A))
|
||||
example.inverse_matrix(A, Ainv_1) # 调用 Fortran 子程序
|
||||
print(Ainv_1)
|
||||
|
||||
Ainv_2 = np.linalg.inv(A)
|
||||
print(Ainv_2)
|
||||
|
||||
print('---')
|
||||
|
||||
# 时间对比
|
||||
|
||||
A = np.random.rand(3000, 3000)
|
||||
|
||||
import time
|
||||
start = time.time()
|
||||
Ainv_1 = np.asfortranarray(np.empty_like(A))
|
||||
example.inverse_matrix(A, Ainv_1) # 调用 Fortran 子程序
|
||||
end = time.time()
|
||||
print('Python + Fortran 求逆时间:', end - start)
|
||||
|
||||
start = time.time()
|
||||
Ainv_2 = np.linalg.inv(A)
|
||||
end = time.time()
|
||||
print('Python np.linalg.inv() 求逆时间:', end - start)
|
@@ -0,0 +1,19 @@
|
||||
! 矩阵求逆子程序
|
||||
subroutine inverse_matrix(A, Ainv)
|
||||
implicit none
|
||||
real(8), intent(in) :: A(:,:) ! 输入矩阵
|
||||
real(8), intent(inout) :: Ainv(:,:) ! 输出逆矩阵
|
||||
real(8), allocatable :: work(:)
|
||||
integer, allocatable :: ipiv(:)
|
||||
integer :: n, info
|
||||
|
||||
n = size(A,1)
|
||||
allocate(ipiv(n), work(n))
|
||||
|
||||
Ainv = A ! 复制输入矩阵
|
||||
|
||||
call dgetrf(n, n, Ainv, n, ipiv, info) ! LU 分解
|
||||
call dgetri(n, Ainv, n, ipiv, work, n, info) ! 计算逆矩阵
|
||||
|
||||
deallocate(ipiv, work)
|
||||
end subroutine inverse_matrix
|
Reference in New Issue
Block a user