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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| #include <stdafx.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <interpolation.h>
using namespace alglib;
void function_cx_1_func(const real_1d_array &c, const real_1d_array &x, double &func, void *ptr)
{
// this callback calculates f(c,x)=exp(-c0*sqr(x0))
// where x is a position on X-axis and c is adjustable parameter
func = exp(-c[0]*pow(x[0],2));
}
int main(int argc, char **argv)
{
//
// In this example we demonstrate exponential fitting
// by f(x) = exp(-c*x^2)
// using function value only.
//
// Gradient is estimated using combination of numerical differences
// and secant updates. diffstep variable stores differentiation step
// (we have to tell algorithm what step to use).
//
real_2d_array x = "[[-1],[-0.8],[-0.6],[-0.4],[-0.2],[0],[0.2],[0.4],[0.6],[0.8],[1.0]]";
real_1d_array y = "[0.223130, 0.382893, 0.582748, 0.786628, 0.941765, 1.000000, 0.941765, 0.786628, 0.582748, 0.382893, 0.223130]";
real_1d_array c = "[0.3]";
double epsf = 0;
double epsx = 0.000001;
ae_int_t maxits = 0;
ae_int_t info;
lsfitstate state;
lsfitreport rep;
double diffstep = 0.0001;
//
// Fitting without weights
//
lsfitcreatef(x, y, c, diffstep, state);
lsfitsetcond(state, epsf, epsx, maxits);
lsfitfit(state, function_cx_1_func);
lsfitresults(state, info, c, rep);
printf("%d\n", int(info)); // EXPECTED: 2
printf("%s\n", c.tostring(1).c_str()); // EXPECTED: [1.5]
//
// Fitting with weights
// (you can change weights and see how it changes result)
//
real_1d_array w = "[1,1,1,1,1,1,1,1,1,1,1]";
lsfitcreatewf(x, y, w, c, diffstep, state);
lsfitsetcond(state, epsf, epsx, maxits);
lsfitfit(state, function_cx_1_func);
lsfitresults(state, info, c, rep);
printf("%d\n", int(info)); // EXPECTED: 2
printf("%s\n", c.tostring(1).c_str()); // EXPECTED: [1.5]
return 0;
} |