Straight Line
Straight Line
THEORY
In curve fitting for a given data, the method of least squares is considered to give the
best fit, with prior knowledge about the shape of the curve. Suppose (x1, y1), (X2, y2),
..., (Xn,yn ) be a set of n observations in an experiment and we wish to fit a straight
line
y = ax + b ……………………….(1)
to these observations. That is, we have to determine the constants a and b, using
the principle of least squares.
For any x (i = 1, 2, ..., n), the expected value of y is axi+ b, while the observed value
of y is yi. Hence, the residuals are
ei = yi - (axi + b), for i = 1, 2, ..., n
2x1 (y1 - ax1 - b) + 2x2 (y2 - ax2 - b) + ... + 2xn (yn – axn - b) = 0
ALGORITHM
Step 1: Read data values x[i],y[i].
Step 2: Compute the sum of powers and products
Σxi, Σxi2, Σyi, Σxiyi
Step 3: Compute a and b
Step 4: Print out the equation.
Step 5: Interpolate the data,if required.
PROGRAM
#include<iostream.h>
#include<math.h>
#include<conio.h>
int main()
{
clrscr();
int n,i;
float X[10],Y[10],sumX=0,sumX2=0,sumY=0,sumXY=0,a,b;
cout<<"How many data points?"<<endl;
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"x["<<i<<"]= " ;
cin>>X[i];
cout<<"y["<<i<<"]= " ;
cin>>Y[i];
}
for(i=1;i<=n;i++)
{
sumX = sumX + X[i];
sumX2 = sumX2 + X[i]*X[i];
sumY = sumY + Y[i];
sumXY = sumXY + X[i]*Y[i];
}
cout<<"\nsumX="<<sumX;
cout<<"\nsumY="<<sumY;
cout<<"\nsumX2="<<sumX2;
cout<<"\nsumXY="<<sumXY;
a = (n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);
b=(sumY-a*sumX)/n;
OUTPUT
How many data points?
6
X1=0.5
Y1=15
X2=1.0
Y2=17
X3=1.5
Y3=19
X4=2.0
Y4=14
X5=2.5
Y5=10
X6=3.0
Y6=7
sumX=10.5
sumY =82
sumX2=22.75
sumXY=127