| [566] | 1 | #define NRANSI
 | 
|---|
 | 2 | #include "nrutil.h"
 | 
|---|
 | 3 | 
 | 
|---|
| [577] | 4 | void lfit(double x[], double y[], double sig[], int ndat, double a[], int ia[],
 | 
|---|
 | 5 |         int ma, double **covar, double *chisq, void (*funcs)(double, double [], int))
 | 
|---|
| [566] | 6 | {
 | 
|---|
| [577] | 7 |         void covsrt(double **covar, int ma, int ia[], int mfit);
 | 
|---|
 | 8 |         void gaussj(double **a, int n, double **b, int m);
 | 
|---|
| [566] | 9 |         int i,j,k,l,m,mfit=0;
 | 
|---|
| [577] | 10 |         double ym,wt,sum,sig2i,**beta,*afunc;
 | 
|---|
| [566] | 11 | 
 | 
|---|
 | 12 |         beta=matrix(1,ma,1,1);
 | 
|---|
| [626] | 13 |         afunc=dvector(1,ma);
 | 
|---|
| [566] | 14 |         for (j=1;j<=ma;j++)
 | 
|---|
 | 15 |                 if (ia[j]) mfit++;
 | 
|---|
 | 16 |         if (mfit == 0) nrerror("lfit: no parameters to be fitted");
 | 
|---|
 | 17 |         for (j=1;j<=mfit;j++) {
 | 
|---|
 | 18 |                 for (k=1;k<=mfit;k++) covar[j][k]=0.0;
 | 
|---|
 | 19 |                 beta[j][1]=0.0;
 | 
|---|
 | 20 |         }
 | 
|---|
 | 21 |         for (i=1;i<=ndat;i++) {
 | 
|---|
 | 22 |                 (*funcs)(x[i],afunc,ma);
 | 
|---|
 | 23 |                 ym=y[i];
 | 
|---|
 | 24 |                 if (mfit < ma) {
 | 
|---|
 | 25 |                         for (j=1;j<=ma;j++)
 | 
|---|
 | 26 |                                 if (!ia[j]) ym -= a[j]*afunc[j];
 | 
|---|
 | 27 |                 }
 | 
|---|
 | 28 |                 sig2i=1.0/SQR(sig[i]);
 | 
|---|
 | 29 |                 for (j=0,l=1;l<=ma;l++) {
 | 
|---|
 | 30 |                         if (ia[l]) {
 | 
|---|
 | 31 |                                 wt=afunc[l]*sig2i;
 | 
|---|
 | 32 |                                 for (j++,k=0,m=1;m<=l;m++)
 | 
|---|
 | 33 |                                         if (ia[m]) covar[j][++k] += wt*afunc[m];
 | 
|---|
 | 34 |                                 beta[j][1] += ym*wt;
 | 
|---|
 | 35 |                         }
 | 
|---|
 | 36 |                 }
 | 
|---|
 | 37 |         }
 | 
|---|
 | 38 |         for (j=2;j<=mfit;j++)
 | 
|---|
 | 39 |                 for (k=1;k<j;k++)
 | 
|---|
 | 40 |                         covar[k][j]=covar[j][k];
 | 
|---|
 | 41 |         gaussj(covar,mfit,beta,1);
 | 
|---|
 | 42 |         for (j=0,l=1;l<=ma;l++)
 | 
|---|
 | 43 |                 if (ia[l]) a[l]=beta[++j][1];
 | 
|---|
 | 44 |         *chisq=0.0;
 | 
|---|
 | 45 |         for (i=1;i<=ndat;i++) {
 | 
|---|
 | 46 |                 (*funcs)(x[i],afunc,ma);
 | 
|---|
 | 47 |                 for (sum=0.0,j=1;j<=ma;j++) sum += a[j]*afunc[j];
 | 
|---|
 | 48 |                 *chisq += SQR((y[i]-sum)/sig[i]);
 | 
|---|
 | 49 |         }
 | 
|---|
 | 50 |         covsrt(covar,ma,ia,mfit);
 | 
|---|
 | 51 |         free_vector(afunc,1,ma);
 | 
|---|
 | 52 |         free_matrix(beta,1,ma,1,1);
 | 
|---|
 | 53 | }
 | 
|---|
 | 54 | #undef NRANSI
 | 
|---|