manpagez: man pages & more
info mathgl
Home | html | info | man
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.7.12 Nonlinear fitting hints

Nonlinear fitting is rather simple. All that you need is the data to fit, the approximation formula and the list of coefficients to fit (better with its initial guess values). Let me demonstrate it on the following simple example (see section Fitting sample). First, let us use sin function with some random noise:

    mglData rnd(100), idl(50); //data to be fitted and ideal data
    rnd.Modify("0.4*rnd+0.1+sin(4*pi*x)");
    idl.Modify("0.3+sin(4*pi*x)");

and plot it to see that data we will fit

    gr->Axis(mglPoint(-1,-2), mglPoint(1,2));
    gr->Plot(rnd, ". "); gr->Plot(idl, "b");
    gr->Box();
    gr->Text(mglPoint(0,2.2), "initial: y = 0.3+sin(2\pi x)", "C:b", -1);

The next step is the fitting itself. For that let me specify an initial values ini for coefficients ‘abc’ and do the fitting for approximation formula ‘a+b*sin(c*x)

    mglData res;   // The data for found formula
    float ini[3] = {1, 1, 3};
    gr->Fit(res, rnd, "a+b*sin(c*x)", "abc", ini);

Now display it

    gr->Plot(res, "r");
    gr->Text(mglPoint(-1,-1.3), "fitted:", "L:r", -1);
    gr->PutsFit(mglPoint(0,-1.8), "y = ", "C:r", -1);

NOTE! the fitting results may have strong dependence on initial values for coefficients due to algorithm features. The problem is that in general case there are several local "optimums" for coefficients and the program returns only first found one! There are no guaranties that it will be the best. Try for example to set ini[3] = {0, 0, 0} in the code above.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]
© manpagez.com 2000-2025
Individual documents may contain additional copyright information.