PROGRAM 6: Curve Fitting to fit a straight line to a given set of data points using Least Square Method If data is in terms of two variables x and y then finding an expression of the type y = f(x) which fits the givens data is called curve fitting. Assume that the given data consists of n points with values of x and y given as (x 1,y 1 ),(x 2,y 2 ),……(x n,y n ) By method Least Squares the data fits to a straight line y = A + B x with B = { n ∑x i y i - ∑x i ∑y i } / { n ∑x i 2 – ( ∑ x i ) 2 } and A = y¯ – B x¯ where y¯ is mean value of variable y x¯ is mean value of variable x
C PROGRAM TO FIT A STRAIGHT LINE Y=A+BX TO A GIVEN SET C OF POINTS DIMENSION X(10),Y(10) WRITE(*,*)’INPUT NUMBER OF DATA POINTS’ READ(*,*)N WRITE(*,*)’INPUT X AND Y VALUES’ DO 10 I =1,N READ(*,*) X(I),Y(I) 10 CONTINUE SX=0.0 SY=0.0 SXY=0.0 SXX=0.0 DO 20 I=1,N SX=SX+X(I) SY=SY+Y(I) SXX=SXX+X(I)*X(I) SXY=SXY+X(I)*Y(I) 20 CONTINUE
X MEAN=SX/N Y MEAN=SY/N DEN=N*SXX-SX*SX B=(N*SXY-SX*SY)/DEN A=Y MEAN-B*X MEAN WRITE(*,*)’THE STRAIGHT LINE OF BEST FIT IS Y=A+BX’ WRITE(*,*)’THE COEFFICIENTS ARE’ WRITE(*,*) ’INTERCEPT A =‘, A WRITE(*,*) ‘SLOPE B =‘, B STOP END