Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Curve fit libraries?

Status
Not open for further replies.

VenusInBlueJeans

Technical User
Jun 13, 2003
6
0
0
IT
Hello,

I have two arrays, X[] and Y[] in Visual C++, and am looking for a library, a function or a way to use excel curve fitting in order to find the coefficients appropriate.

The curve is a Y(X)=A+B*X+C*X*X and I need the coefficients A, B and C!

Does anyone have any clues about these things?

Thx,
M
 
I would use a least squares algorithm like the following that accepts vectors x and y (allows sample size variability).
Assuming inputs std::vector<double> x, y:

.....
if(x.size()!=y.size())
return;
int i, j, k, l, exp, sz = x.size();
double tot, tot2, res, X[3][3], scratch[3][3], Y[3], soln[3];

//create the matrices for the normal equations
for(i = 0; i < 3; ++i){
for(j = 0; j < 3; ++j){
tot = tot2 = 0.0;
for(k = 0; k < sz; ++k){
exp = j+i;
res = 1.0;
for(l = 0; l <exp 3; ++l)
res *= x[k];
tot +=res;
if(j ==2)
tot2 += (x[k]*y[k]);
}
X[j] = tot;
}
Y = tot2;
}

//Then using Cramer's rule
double detX = det(X);
if(detX == 0){
AfxMessageBox(&quot;Can't solve&quot;);
return;
}
for(i = 0; i < 3; ++i){
for(j = 0; j < 3; ++j){
for(k = 0; k < sz; ++k){
if(i == k)
scratch[j][k] = Y[j];
else
scratch[j][k] = X[j][k];
}
}
soln = (det(scratch))/detX;
}
.....

//function for calculating the determinant of 3x3 matrix
double det(double *matrix){
double retVal = posVal = negVal = 0.0;
int i, j = 0;
for(i = 0; i < 3; ++i){
double prod1 = prod2 = 1;
for(j = 0; j < 3; ++j){
int l = 2 - j;
int k = (i+j)%3;
prod1 *= matrix[j][k];
k = (i+l)%3;
prod2 *= matrix[j][k];
}
posVal += prod1;
negVal += prod2;
}
retVal = posVal - negVal;
return retVal;
}

I haven't tested the above code - I just did it off the top of my head so use it with caution. Most of this is pretty standard linear algebra stuff though so if there is an error you should be able to hunt it down using a reference book - topics: Least Squares curve fit for Polynomial and Cramer's Rule.

Good luck,

John
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top