Fortran,LU方法无法让它工作正常

时间:2014-09-16 23:47:07

标签: fortran

我正在做一个强大的功课,我必须编写LU方法,我写了一些行,但我被卡住,因为它不能正常工作。 我的程序在阵列1和2以及U中表现良好,而第1列和第2列表示L,但3和4表示错误(L和U)。 你能帮我吗? 这是该计划:

program lu
implicit none
real*8 A(4,4),L(4,4),U(4,4)
integer i,j,n,k
open(unit=21,file='mat2.dat')
open(unit=22,file='L.dat')
open(unit=23,file='U.dat')
A=0.0d0
L=0.0d0
U=0.0d0
do i=1,4
    read(21,*) (A(i,j),j=1,4) !read A matrix
end do
do i=1,4
L(i,1)=A(i,1) !creating array L(i,1)
U(1,i)=A(1,i)/L(1,1) !creating row U(1,i)
end do
do i=2,4
 do j=2,4
  if(i.eq.j) then
   U(i,j)=1 !creating U diagonal=1, since U(1,1) is already created it can start from 2
  end if 
  do n=1,j-1
   if (i>=j) then
    L(i,j)=A(i,j)-L(i,n)*U(n,j) !creating the L missing part, i think here is an error, but i can't find it
   end if
  end do 
  do n=1,i-1
   if (i<j) then
    U(i,j)=A(i,j)*1/L(i,i)-L(i,n)*U(n,j)*1/L(i,i) !creating the U missing part
   end if
  end do
 end do
end do  
do i=1,4
 write(22,*) (L(i,j),j=1,4) !write to check if it's working fine
 write(23,*) (U(i,j),j=1,4)
end do
end program

这是A矩阵

3 -1 4 -1
-1 -1 3 1
2 3 -1 -1
7 1 1 2

L和U应该看起来像这张照片 http://i.cubeupload.com/J6u1VN.png 抱歉我的英语不好:(

1 个答案:

答案 0 :(得分:0)

通常,将L和U存储在一个唯一的矩阵中,通常,只需修改用作输入和输出的初始矩阵。

算法相当简单;这是一个没有数据透视搜索的变种:

SUBROUTINE matrix_lu(matrix)

   ! decomposing a matrix as a product of two triangular matrices (lower and upper)
   ! the diagonal belongs to the upper triangular matrix (the diagonal of the lower
   ! triangular matrix is assumed to be equal to the identity matrix)

   ! Take care : the diagonal of U is already inversed

   DOUBLE PRECISION, INTENT(inout) :: matrix(:,:)
   INTEGER :: n,i,k,l

   n=SIZE(matrix,1)

   DO k = 1, n
      matrix(k, k) = 1.d0/matrix(k, k)
      DO i = k+1, n
         matrix(i, k) = matrix(i, k)*matrix(k, k)
      ENDDO
      DO l = k+1, n
         DO i = k+1, n
            matrix(i, l) = matrix(i, l)-matrix(i, k)*matrix(k, l)
         END DO
      END DO
   END DO

END SUBROUTINE

所以我不理解你算法中的几件事:

  • j上的第二个循环应该是从i到n(或i + 1到n):

  • 循环中没有测试

  • 全局复杂度(乘法次数)为n ^ 3/3。您的算法在n ^ 3