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