Anda di halaman 1dari 2

File: /home/himanshu/fortran/gauss.

f95 Page 1 of 2

! program fo ques 4, in this i will obtain a diagonal matrix instead of a upper


triangular matrix, i will also normalise all the pivots to 1, so that we can read
the last column as solution

program gauss
implicit none
real(8), dimension(41,42) :: a,b ! declaring matrix a to store all elements and b
for swapping
integer :: i,j,k
logical :: lo;lo=.true.

a(1:41,1:42)=0
a(1,1)=1
a(1,42)=-0.5
a(41,41)=1
a(41,42)=log(2.0)
do i=2,40
a(i,i+1)=(0.025**(-2))+4*((1+0.025*(i-1))*0.025)**(-1)
a(i,i)=-2*(0.025)**(-2)-4*((1+0.025*(i-1))*0.025)**(-1)-2*(1+0.025*(i-1))**(-2)
a(i,i-1)=(0.025)**(-2)
end do ! assignment to all matrix elements according to the given difference
equation

iloop: do i=1,41
! finding pivot
jloop: do j=i,41
if(a(j,j).ne.0) then
exit jloop
end if
end do jloop ! if non zero value is found in the ith column then loop
exits, and value of j is not incremented to 42

if (j.eq.42) then
print*,'no solution'
exit iloop
end if ! in above loop if j reaches 42 it means no non zero element was
found, hence unique sol. is not possible

if(j.ne.i) then
call replace(a,b,i,j) ! calling a subroutine to swap the ith row
with the row having nonzero element
end if

call strike(a,i) ! makes all the elements in a ith column zero other than
pivot

do k=1,41 ! this and the next are extra steps, they normalise all
the pivots to 1,
if(a(k,k).eq.0) then
lo=.false.
print*,"error"
end if
end do ! checking if any pivots are zero, so we don't divide by 0 while
normalising.

if(lo) then
call norm(a)
end if
end do iloop

do i=1,41
write(11,*) (1+0.025*(i-1)), a(i,42) ! all the answers are written to fort.
11
print*, (1+0.025*(i-1)), a(i,42)
end do
File: /home/himanshu/fortran/gauss.f95 Page 2 of 2

end program

subroutine replace(a,b,i,j) ! subroutine to swap


real(8), dimension(41,42) :: a,b
integer i,j
b(1,1:42)=a(i,1:42)
a(i,1:42)=a(j,1:42)
a(j,1:42)=b(1,1:42)
end subroutine

subroutine strike(a,i) ! subroutine to make all elements zero other than pivot in
the given column
real(8), dimension(41,42) :: a
integer i,j
do j=1,41
if (i.ne.j) then
a(j,1:42)=a(j,1:42)-(a(j,i)/a(i,i))*a(i,1:42)
end if
end do
end subroutine

subroutine norm(a) ! subroutine to normalise al pivots


real(8), dimension(41,42) :: a
integer i
do i=1,41
a(i,1:42)=a(i,1:42)/a(i,i)
end do
end subroutine

Anda mungkin juga menyukai