C++ program for curve fitting of linear and exponential equation
For linear:
#include<iostream>
using namespace std;
class datacalc
{
private:
float sumxsq,sumxy,sumx,sumy;
float valuex[50],valuey[50];
float a,b;
int i,n;
public:
void getdata()
{
cout<<"enter the no. of data to input:";
cin>>n;
cout<<"enter the value for x and y:"<<endl;
for(i=0;i<n;i++)
{
cin>>valuex[i]>>valuey[i];
}
}
void calculate()
{
sumxsq=0,sumxy=0,sumx=0,sumy=0;
for(i=0;i<n;i++)
{
sumx=sumx+valuex[i];
sumy=sumy+valuey[i];
sumxy=sumxy+valuex[i]*valuey[i];
sumxsq=sumxsq+valuex[i]*valuex[i];
a=(sumy*sumxsq-sumx*sumxy)/(n*sumxsq-sumx*sumx);
b=(n*sumxy-sumx*sumy)/(n*sumxsq-sumx*sumx);
}
}
void display()
{
cout<<"the value of a and b are:"<<a<<" , "<<b<<endl;
cout<<"the required equation is:"<<endl<<"y="<<a<<"+"<<b<<"x";
}
};
int main()
{
datacalc d1;
d1.getdata();
d1.calculate();
d1.display();
return 0;
}
For exponential:
#include<iostream>
#include<cmath>
using namespace std;
class datacalc
{
private:
float sumxsq,sumxy,sumx,sumy;
float valuex[50],valuey[50];
float a,b,A;
int i,n;
public:
void getdata()
{
cout<<"enter the no. of data to input:";
cin>>n;
cout<<"enter the value for x and y:"<<endl;
for(i=0;i<n;i++)
{
cin>>valuex[i]>>valuey[i];
}
}
void calculate()
{
sumxsq=0,sumxy=0,sumx=0,sumy=0;
for(i=0;i<n;i++)
{
sumx=sumx+valuex[i];
sumy=sumy+log(valuey[i]);
sumxy=sumxy+valuex[i]*log(valuey[i]);
sumxsq=sumxsq+valuex[i]*valuex[i];
A=(sumy*sumxsq-sumx*sumxy)/(n*sumxsq-sumx*sumx);
b=(n*sumxy-sumx*sumy)/(n*sumxsq-sumx*sumx);
a=exp(A);
}
}
void display()
{
cout<<"the value of a and b are:"<<a<<" , "<<b<<endl;
cout<<"the required equation is:"<<endl<<"y="<<a<<"exp("<<b<<"x)";
}
};
int main()
{
datacalc d1;
d1.getdata();
d1.calculate();
d1.display();
return 0;
}