Newton Forward Interpolation Method | FORTRAN 95

Fortran Programming - Bottom Science

 

NOTE – CREATE the ‘data.txt’ file in your program folder before running the program.

data.txt

100   10.63
150   13.03
200   15.04
250   16.81
300   18.42
350   19.90
400   21.27

Fortran Code

PROGRAM newton_forward
IMPLICIT NONE
INTEGER::i,j,n,ierror,factfun
REAL::x(20),y(20),dt(20,20),t,p,s,pro
OPEN(UNIT=1, FILE='data.txt', STATUS='UNKNOWN', ACTION='READ', IOSTAT=ierror)

PRINT *, "============================================" 
PRINT *, "Program for Newton forward interpolation method - [BY - www.BottomScience.com]" 
PRINT *, "============================================"
PRINT *,'DIFFERENCE TABLE'
PRINT *,'Number of values?'
READ(*,*)n
PRINT *,'Value at which we want calculation?'
READ(*,*)t
PRINT *,'Storing values in x and y arrays....'
READ(1,*)(x(i),y(i),i=1,n)
CLOSE(1)
CALL diff_table(y,dt,n)
!PRINTING
DO j=1,n-1
  WRITE(*,*)(dt(j,i),i=1,n-j)
END DO
!VALUE OF FUNCTION
p=(t-x(1))/(x(2)-x(1))
s=y(1)
DO i=1,n-1
  pro=1.0
  DO j=0,i-1
    pro=pro*(p-j)
  END DO
  s=s+(dt(1,j)*(pro/factfun(i)))
END DO
PRINT *,"================================================="
PRINT *,"CALCULATED VALUE OF DIVIDED DIFFERENCE AT",t,"-",s
END PROGRAM
!CALCULATING FORWARD DIFFERENCES
SUBROUTINE diff_table(y1,dt1,n1)
INTEGER::i1,j1,n1
REAL::y1(20),dt1(20,20)
DO j1=1,n1-1
  DO i1=1,n1-j1
    IF(j1==1) THEN
      dt1(i1,j1)=(y1(i1+1)-y1(i1))
    ELSE
      dt1(i1,j1)=(dt1(i1+1,j1-1)-dt1(i1,j1-1))
    END IF
  END DO
END DO
RETURN
END SUBROUTINE
INTEGER function factfun(n1)
INTEGER::n1,fact1
  fact1=1
  do i1=1,n1
    fact1=fact1*i1
  end do
  factfun=fact1
return
end function

Leave a Reply

Your email address will not be published.