You are on page 1of 1

C++ Program for Curve Fitting using least square methods for straight line

#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"\nEnter number of data pairs:\n";
cin>>n;
float x[n], y[n];
cout<< "Calculating the best fit value using least square method for y=ax+b.\n";
for (int i=0; i<n; i++)
{
cout<<" Data " << i+1 << " :\n";
cout<<"x: ";
cin>>x[i];
cout<<"y: ";
cin>>y[i];
}
cout<< "\n\nData input completed.\n\nThe value table: "<<endl<<endl;
float sumy=0, sumx=0, sumxy=0, sumxx=0;
cout<<"x\ty\txx\txy\n";
for (int i=0; i<n; i++)
{
sumy+= y[i];
sumx+= x[i];
sumxx+= x[i]*x[i];
sumxy+= y[i]*x[i];
}
cout<<endl;
for (int i=0; i<n; i++)
{
cout<<x[i]<<"\t"<<y[i]<<"\t"<<x[i]*x[i]<<"\t"<<y[i]*x[i]<<endl;
}

cout<<"\n\nThe calculated value of sumx, sumy, sumxx, sumxy is : " << sumx<< ","<< sumy<<
","<< sumxx<< " and "<< sumxy<< "."<< endl;
float a=(sumx*sumxy-sumy*sumxx)/(sumx*sumx-n*sumxx);
float b=(sumy*sumx-n*sumxy)/(sumx*sumx-n*sumxx);

cout<<"\n\nThe calculated value of a and b is : "<< a<< " and "<< b<< "."<<endl;
cout<<"\n\nThe best fit value of curve is : y = "<< a<< " + "<< b<< "x.\n\n"<<endl;

You might also like