Linear Least Square 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 least_square
IMPLICIT NONE
INTEGER::ierror,n,i
REAL::m,x(20),y(20),x_avg,y_avg
REAL::s_x=0.0,s_x2=0.0,s_y=0.0,s_xy=0.0,c 

OPEN(UNIT=1, FILE='data.txt', STATUS='UNKNOWN', ACTION='READ', IOSTAT=ierror)

PRINT *,'================'
PRINT *,'Program for fitting curve using linear least square method [www.BottomScience.com]'
PRINT *,'================'

PRINT *,'Number of values?'
READ(*,*)n

PRINT *,'Storing values in x and y arrays from the file....'

READ(1,*)(x(i),y(i),i=1,n)
CLOSE(1)

DO i=1,n
  s_x=s_x+x(i)
  s_y=s_y+y(i)
  s_xy=s_xy+(x(i)*y(i))
  s_x2=s_x2+(x(i)**2)
END DO

x_avg=s_x/n
y_avg=s_y/n
m=((n*s_xy)-(s_x*s_y))/((n*s_x2)-(s_x**2))
c=y_avg-(m*x_avg)
PRINT *,'Slope is -',m
PRINT *,'Constant is -',c

PRINT *,'Values at different data points:'
DO i=1,n 
y(i)=(m*x(i))+c
WRITE(*,*) x(i),y(i)
END DO

END PROGRAM

Leave a Reply

Your email address will not be published.