Advertisement
parthosutradhor

LU factorization

Apr 23rd, 2019
1,149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. program LU
  2.     implicit none
  3.     integer, parameter:: n=3
  4.     integer:: i, j, k
  5.     real:: A(n,n), b(n), x(n), y(n), L(n,n), U(n,n), s
  6.  
  7.     !reading
  8.     open(11, file="in.txt")
  9.  
  10.     do i=1,n
  11.         read(11,*) (A(i,j), j=1,n)
  12.     end do
  13.  
  14.     read(11,*) (b(i), i=1,n)
  15.  
  16.     close(11)
  17.  
  18.     ! initializing 1st row of U and 1st column of L
  19.     L(1,1)=1.0
  20.     U(1,1)=A(1,1)
  21.  
  22.     if(A(1,1)==0.0) then
  23.         write(*,*) "Impossible to find solution"
  24.         stop
  25.     end if
  26.  
  27.     do i=2,n
  28.         U(1,i)=A(1,i)/L(1,1)
  29.         L(i,1)=A(i,1)/U(1,1)
  30.     end do
  31.  
  32.  
  33.     !
  34.     do i=2,n-1
  35.  
  36.         L(i,i)=1.0
  37.         s=0.0
  38.         do k=1,i-1
  39.             s=s+L(i,k)*U(k,i)
  40.         end do
  41.         U(i,i)=A(i,i)-s
  42.  
  43.         if(A(i,i)==0.0) then
  44.             write(*,*) "Impossible to find solution"
  45.             stop
  46.         end if
  47.  
  48.         do j=i+1,n
  49.  
  50.             s=0.0
  51.             do k=1,i-1
  52.                 s=s+L(i,k)*U(k,j)
  53.             end do
  54.             U(i,j)=A(i,j)-s
  55.  
  56.             s=0.0
  57.             do k=1,i-1
  58.                 s=s+L(j,k)*U(k,i)
  59.             end do
  60.             L(j,i)=(A(j,i)-s)/U(i,i)
  61.  
  62.         end do
  63.  
  64.     end do
  65.  
  66.     L(n,n)=1.0
  67.     s=0.0
  68.     do k=1,n-1
  69.         s=s+L(n,k)*U(k,n)
  70.     end do
  71.     U(n,n)=A(n,n)-s
  72.  
  73.  
  74.     open(12,file="out.txt")
  75.  
  76.     write(12,*)"Matrix L"
  77.     do i=1,n
  78.         write(12,*) (L(i,j), j=1,n)
  79.     end do
  80.  
  81.     write(12,*)""
  82.     write(12,*)"Matrix U"
  83.     do i=1,n
  84.         write(12,*) (U(i,j), j=1,n)
  85.     end do
  86.  
  87.     ! forward substitution
  88.     y(1)=b(1)
  89.     do i=2,n
  90.         s=0.0
  91.         do j=1,i-1
  92.             s=s+L(i,j)*y(j)
  93.         end do
  94.         y(i)=b(i)-s
  95.     end do
  96.  
  97.  
  98.     ! backward substitution
  99.     x(n)=y(n)/U(n,n)
  100.     do i=n-1,1,-1
  101.         s=0.0
  102.         do j=n,i+1,-1
  103.             s=s+U(i,j)*x(j)
  104.         end do
  105.         x(i)=(y(i)-s)/U(i,i)
  106.     end do
  107.  
  108.     write(12,*)""
  109.     write(12,*)"solution is: "
  110.     write(12,*) (x(i), i=1,n)
  111.  
  112.     close(12)
  113.  
  114. end program LU
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement