Menu Close

Least Squares Method C++

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
float augm[3][4]={{0,0,0,0},{0,0,0,0},{0,0,0,0}};
int i,j,k,n;
float t,a,b,c,x,y,xsq;

cout<<"Enter the no. of pairs of ";
cout<<"observed values:"<<endl;
cin>>n;

cout<<fixed;

augm[0][0]=n;

for(i=0;i<n;i++)
{
cout<<"Pair no."<<i+1<<endl;
cin>>x>>y;

xsq=x*x;
augm[0][1] += x;
augm[0][2] += xsq;
augm[1][2] += x*xsq;
augm[2][2] += xsq*xsq;
augm[0][3] += y;
augm[1][3] += x*y;
augm[2][3] += xsq*y;
}

augm[1][1] += augm[0][2];
augm[2][1] += augm[1][2];
augm[1][0] += augm[0][1];
augm[2][1] += augm[1][1];

cout<<"The augmented matrix is:-"<<endl;

for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
cout<<setw(9)<<setprecision(4)<<augm[i][j];
cout<<endl;
}

//Solving for a,b,c by Gauss Jorden Method

for(j=0;j<3;j++)
for(i=0;i<3;i++)
if(i != j)
{
t=augm[i][j]/augm[j][j];
for(k=0;k<4;k++)
augm[i][k] -= augm[j][k]*t;
}
a=augm[0][3]/augm[0][0];
a=augm[1][3]/augm[1][1];
a=augm[2][3]/augm[2][2];

cout<<setprecision(4);
cout<<"a= "<<setw(8)<<a;
cout<<"b= "<<setw(8)<<b;
cout<<"c= "<<setw(8)<<c;
cout<<endl;

return 0;
}

Output

Enter the no. of pairs of observed values:
5
Pair no.1
1 1.2
Pair no.2
1.5 2.4
Pair no.3
2 1.7
Pair no.4
2.5 2.1
Pair no.5
3 2.8
The augmented matrix is:-
5.0000 10.0000 22.5000 10.2000
10.0000 22.5000 55.0000 21.8500
0.0000 77.5000 142.1250 51.7250
a= -0.0404b= 0.0000c= 0.0000

More Related Stuff