Method of least square fit of straight line to a given set of data points. Fortran program is attached. This is for beginners and students. Remember, the method of least squre fit for any non linear function is non-trivial. For that you may consult Numerical Recipe or any other good book on Numerical computation book.
Comments
Content
1
Least square fit of a straight line to data:
The equation of a straight line is
b mx y + ·
Consider the data points (
1 1
, y x ) , (
2 2
, y x )…….etc.
Error is defined as
2
1
) ( ) , (
i i
n
i
y b x m b m − + ·
∑
·
ε
.
For the best fit, this error should be minimum.
Therefore, 0 ·
∂
∂
m
ε
and 0 ·
∂
∂
b
ε
.
Now,
]
]
]
− +
∂
∂
·
∂
∂
∑
·
2
1
) (
n
i
i i
y b mx
m m
ε
=
2
1
) (
i i
n
i
y b x m
m
− +
∂
∂
∑
·
=
) ( ) .( 2
1
i i i i
n
i
y b mx
m
y b x m − +
∂
∂
− +
∑
·
=
i i
n
i
i
x y b mx ) ( 2
1
− +
∑
·
=
i
n
i
i
n
i
i
n
i
i
x y x b x m
∑ ∑ ∑
· · ·
− +
1 1 1
2
2 2
= 0 (1)
Similarly,
∑ ∑
· ·
· + · ·
∂
∂
n
i
i
n
i
i
y nb x m
b
1 1
0
ε
(2)
From (1) and (2),
,
`
.
|
·
,
`
.
|
,
`
.
|
∑
∑
∑ ∑
∑
·
·
· ·
·
n
i
i i
n
i
i
n
i
i
n
i
i
n
i
i
x y
y
m
b
x x
x n
1
1
1
2
1
1
Slope,
∑ ∑
∑ ∑ ∑
· ·
· · ·
−
−
·
n
i
n
i
i i
n
i
n
i
n
i
i i i i
x x n
x y y x n
m
1
2
1
2
1 1 1
) (
and Intercept,
∑ ∑
∑ ∑ ∑ ∑
· ·
· · · ·
−
−
·
n
i
n
i
i i
n
i
n
i
n
i
i i i
n
i
i i
x x n
y x x x y
b
1
2
1
2
1 1 1 1
2
) (
.
Example:
For the data points (1,2), (2,3), (3,4), (4,5)
4 · n ,
10 4 3 2 1
1
· + + + ·
∑
·
n
i
i
x
,
14 5 4 3 2
1
· + + + ·
∑
·
n
i
i
y
40 5 4 4 3 3 2 2 1
1
· × + × + × + × ·
∑
·
n
i
i i
y x
,
30 4 4 3 3 2 2 1 1
1
2
· × + × + × + × ·
∑
·
n
i
i
x
∴ 1
20
20
100 120
140 160
10 30 4
10 14 40 4
2
· ·
−
−
·
− ×
× − ×
· m
,
1
20
20
100 120
400 420
10 30 4
40 10 30 14
2
· ·
−
−
·
− ×
× − ×
· b
.
2
FORTRAN PROGRAM FOR LEAST SQUARE FITTING:
C Least square fitting of a straight line to data points
write(*,*)'Give the Number of Points'
read(*,*)n
write(*,*)'Write the data points: x,y'
sumx=0.0
sumy=0.0
sumsqx=0.0
sumxy=0.0
do i=1,n
read(*,*)x,y
sumx=sumx+x
sumy=sumy+y
sumsqx=sumsqx+x*x
sumxy=sumxy+x*y
enddo
deno=n*sumsqx-sumx*sumx
slope=(n*sumxy-sumx*sumy)/deno
b=(sumsqx*sumy-sumx*sumxy)/deno
write(*,*)'Slope, Intercept= ',slope,b
stop
end