[Fortran] 纯文本查看 复制代码
module inv
contains
subroutine inverse(a, n ,l)
implicit none
real(kind=8) :: a(n,n)
integer(kind=4) :: is(n), js(n)
real(kind=8) :: t, d
integer :: i, j, k, n, l
l=1
do k=1, n
d=0.0
do i=k, n
do j=k, n
if (abs(a(i,j)).gt.d) then
d=abs(a(i,j))
is(k)=i
js(k)=j
end if
end do
end do
if (d+1.0.eq.1.0) then
l=0
write(*, '(1x, "Err ** not inv")')
return
end if
do j=1, n
t = a(k, j)
a(k, j) = a(is(k),j)
a(is(k),j) = t
end do
do i=1, n
t=a(i,k)
a(i,k)=a(i,js(k))
a(i,js(k))=t
end do
a(k,k)=1/a(k,k)
do j=1,n
if (j.ne.k) then
a(k,j)=a(k,j)*a(k,k)
end if
end do
do i = 1, n
if (i.ne.k) then
do j=1, n
if (j.ne.k) then
a(i,j)=a(i,j)-a(i,k)*a(k,j)
end if
end do
end if
end do
do i=1,n
if (i.ne.k) then
a(i,k)=-a(i,k)*a(k,k)
end if
end do
end do
do k=n,1,-1
do j=1,n
t=a(k,j)
a(k,j)=a(js(k),j)
a(js(k),j)=t
end do
do i=1,n
t=a(i,k)
a(i,k)=a(i,is(k))
a(i,is(k))=t
end do
end do
return
end subroutine inverse
end module inv
program main
use inv
implicit none
real(kind=8), allocatable :: a(:,:),b(:,:),re(:,:)
integer :: i, j, n, l
real(kind=8) :: u
real(kind=4) :: t1, t2
n = 4000
allocate(a(n,n),b(n,n))
do i=1,n
do j=1,n
call random_number(u)
a(i,j) = u * 3.0
enddo
enddo
b=a
! 随机矩阵求逆,再乘以原矩阵,得到单位阵。
print *, "N=", n
print *, "正在计算... ..."
call cpu_time(t1)
call inverse(a, n, l)
re = matmul(a, b)
call cpu_time(t2)
do i=1,min(10,n)
write(*,'(10(f10.3,x))') re(i, 1:min(10,n))
enddo
print *, "Matmul Time: ", t2-t1, "秒"
end program main
! gfortran -O3 array_inv_mul_original.f90 -L./lapack -llapack -lrefblas -o array_inv_mul_original.exe
!