Curve
fitting is the process to fit a curve (or a function) to a given set of data.
This method is useful to perform over inaccurate data. In this method, we fit a
function to the experimental data that is unambiguous and that in some sense
minimizes the deviations of the point from the function curve. The usual method
for doing this is called the “least square method”. The deviations are
determined by the distance between the points and the line of the function. How
these distances are measured depends on whether there are experimental errors
in both variables or in just one of them.
Source Code for least square method
(for exponential equation)
// Example : a *
eb x
#include<iostream>
#include<cmath>
using namespace
std;
int main()
{
float *x, *y, sum_x=0, sum_y=0, sum_xy=0,
sum_xx=0, del, del1, del2, a, b;
int size;
cout<<"Enter the size of data :
";
cin>>size;
x = new float[size];
y = new float[size];
for (int i = 0;
i < size; i++)
{
cout<<"Enter the value of x and
its respective y :";
cin>>x[i]>>y[i];
sum_x += x[i];
sum_y += log(y[i]);
sum_xx += x[i]*x[i];
sum_xy += x[i]*log(y[i]);
}
del = pow(sum_x,2) - sum_xx*size;
del1 =
sum_x*sum_y - sum_xy*size;
del2 =
sum_x*sum_xy - sum_y*sum_xx;
b = del1/del; a = exp(del2/del);
cout<<"a =
"<<a<<" and b = "<<b<<endl;
return 0;
}
(for linear equation)
// Example : a * x + b
#include<iostream>
#include<cmath>
using namespace std;
int main(){
float *x, *y,
sum_x=0, sum_y=0, sum_xy=0, sum_xx=0, del, del1, del2, a, b;
int size;
cout<<"Enter the size of data :
";
cin>>size;
x = new float[size];
y = new float[size];
for (int i = 0; i < size; i++){
cout<<"Enter the value of x
and its respective y :";
cin>>x[i]>>y[i];
sum_x += x[i];
sum_y += y[i];
sum_xx += x[i]*x[i];
sum_xy += x[i]*y[i];
}
del = pow(sum_x,2) - sum_xx*size;
del1 = sum_x*sum_y - sum_xy*size;
del2 = sum_x*sum_xy - sum_y*sum_xx;
a = del1/del; b = del2/del;
cout<<"a =
"<<a<<" and b = "<<b<<endl;
return 0;
}
Note: Above both programs are written in code blocks
using C++ programming.
No comments:
Post a Comment