Last active
May 8, 2018 07:24
-
-
Save ivankp/2d0d31e0478b28ac184a402d04627b46 to your computer and use it in GitHub Desktop.
Test of gsl_multifit_linear chi2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // gcc -Wall -g $^ -o $@ -lm -lgsl -lgslcblas | |
| // https://www.gnu.org/software/gsl/doc/html/lls.html?highlight=gsl_multifit_linear#c.gsl_multifit_linear | |
| #include <math.h> | |
| #include <gsl/gsl_multifit.h> | |
| #define nx 30 | |
| #define np 3 | |
| int main(int argc, char* argv[]) { | |
| double x[nx] = { | |
| 1,2,3,4,5,6,7,8,9,10, | |
| 11,12,13,14,15,16,17,18,19,20, | |
| 21,22,23,24,25,26,27,28,29,30 }; | |
| double y[nx] = { // y = f*(1.05-0.1*RAND()); f = p0 + p1 x + p2 x^2 | |
| 8,14,23,31,46,56,73,91,107,131, | |
| 156,179,206,247,264,313,347,379,427,481, | |
| 506,557,630,672,700,787,835,879,916,1031 }; | |
| double p[np]; | |
| gsl_multifit_linear_workspace *ws; | |
| gsl_matrix *cov, *mx; | |
| gsl_vector *vy, *vp; | |
| ws = gsl_multifit_linear_alloc(nx,np); | |
| mx = gsl_matrix_alloc(nx,np); | |
| vy = gsl_vector_alloc(nx); | |
| vp = gsl_vector_alloc(np); | |
| cov = gsl_matrix_alloc(np,np); | |
| for (int i=0; i < nx; ++i) { | |
| for (int j=0; j < np; ++j) | |
| gsl_matrix_set(mx, i, j, pow(x[i],j)); | |
| gsl_vector_set(vy, i, y[i]); | |
| } | |
| double chi2; | |
| gsl_multifit_linear(mx, vy, vp, cov, &chi2, ws); | |
| printf("gsl chi2 = %f\n",chi2); | |
| for (int i=0; i < np; ++i) { | |
| p[i] = gsl_vector_get(vp,i); | |
| printf("p%i = %f\n",i,p[i]); | |
| } | |
| chi2 = 0; | |
| for (int i=0; i<nx; ++i) { | |
| double f = p[0] + p[1]*x[i] + p[2]*x[i]*x[i]; | |
| chi2 += pow(y[i]-f,2)/y[i]; | |
| } | |
| printf("expected chi2 = %f\n",chi2); | |
| gsl_vector_free(vp); | |
| gsl_vector_free(vy); | |
| gsl_matrix_free(mx); | |
| gsl_matrix_free(cov); | |
| gsl_multifit_linear_free(ws); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment