1 /* 2 * Library: lmfit (Levenberg-Marquardt least squares fitting) 3 * 4 * File: demo/curve1.c 5 * 6 * Contents: Example for fitting data with error bars: 7 * fit a data set (x,y+-dy) by a curve f(x;p). 8 * 9 * Author: Joachim Wuttke <j.wuttke@fz-juelich.de> 2004-2013 10 * 11 * Licence: see ../COPYING (FreeBSD) 12 * 13 * Homepage: apps.jcns.fz-juelich.de/lmfit 14 */ 15 16 #include "lmcurve_tyd.h" 17 #include <stdio.h> 18 19 /* model function: a parabola */ 20 21 double f( double t, const double *p ) 22 { 23 return p[0] + p[1]*t + p[2]*t*t; 24 } 25 26 int main() 27 { 28 int n = 3; /* number of parameters in model function f */ 29 double par[3] = { 100, 0, -10 }; /* really bad starting value */ 30 31 /* data points: a slightly distorted standard parabola */ 32 int m = 9; 33 int i; 34 double t[9] = { -4., -3., -2., -1., 0., 1., 2., 3., 4. }; 35 double y[9] = { 16.6, 9.9, 4.4, 1.1, 0., 1.1, 4.2, 9.3, 16.4 }; 36 double dy[9] = { 4, 3, 2, 1, 2, 3, 4, 5, 6 }; 37 38 lm_control_struct control = lm_control_double; 39 lm_status_struct status; 40 control.verbosity = 1; 41 42 printf( "Fitting ...\n" ); 43 /* now the call to lmfit */ 44 lmcurve_tyd( n, par, m, t, y, dy, f, &control, &status ); 45 46 printf( "Results:\n" ); 47 printf( "status after %d function evaluations:\n %s\n", 48 status.nfev, lm_infmsg[status.outcome] ); 49 50 printf("obtained parameters:\n"); 51 for ( i = 0; i < n; ++i) 52 printf(" par[%i] = %12g\n", i, par[i]); 53 printf("obtained norm:\n %12g\n", status.fnorm ); 54 55 printf("fitting data as follows:\n"); 56 for ( i = 0; i < m; ++i) 57 printf( 58 " t[%1d]=%2g y=%5.1f+-%4.1f fit=%8.5f residue=%8.4f weighed=%8.4f\n", 59 i, t[i], y[i], dy[i], f(t[i],par), y[i] - f(t[i],par), 60 (y[i] - f(t[i],par))/dy[i] ); 61 62 return 0; 63 } 64