9 double *x, *y; /* length N; */
12 static double sqr(double x) { return x * x; }
16 static double lorentzerr(int n, const double *p, double *grad, void *data)
18 lorentzdata *d = (lorentzdata *) data;
20 const double *xs = d->x;
21 const double *ys = d->y;
25 for (i = 0; i < N; ++i) {
26 double x = xs[i], y = ys[i];
29 for (j = 0; j < n; j += 3) {
33 double lor = A / (sqr(x - w) + G*G);
38 val += sqr(y - lorsum);
41 for (j = 0; j < n; j += 3) {
45 double deninv = 1.0 / (sqr(x - w) + G*G);
47 grad[j + 0] += -2 * (y - lorsum) * deninv;
48 grad[j + 1] += 4*A * (w - x) * (y - lorsum) * sqr(deninv);
49 grad[j + 2] += 4*A * G * (y - lorsum) * sqr(deninv);
53 // printf("%d: f(%g,%g,%g) = %g\n", count, p[0],p[1],p[2], val);
57 extern double nlopt_urand(double a, double b);
63 double A = 1, w = 0, G = 1, noise=0.01;
64 double lb[3] = {-HUGE_VAL,-HUGE_VAL,0};
65 double ub[3] = {HUGE_VAL,HUGE_VAL,HUGE_VAL};
66 double p[3] = {0,1,2}, minf;
71 d.x = (double *) malloc(sizeof(double) * d.N * 2);
73 for (i = 0; i < d.N; ++i) {
74 d.x[i] = nlopt_urand(-0.5, 0.5) * 8*G + w;
75 d.y[i] = 2*noise*nlopt_urand(-0.5,0.5) + A / (sqr(d.x[i]-w) + G*G);
78 nlopt_minimize(NLOPT_LN_NEWUOA_BOUND, 3, lorentzerr, &d,
80 -HUGE_VAL, 0,0, 1e-6,NULL, 0,0);
82 printf("%d minf=%g at A=%g, w=%g, G=%g\n", count, minf, p[0],p[1],p[2]);
85 nlopt_minimize(NLOPT_LN_COBYLA, 3, lorentzerr, &d,
87 -HUGE_VAL, 0,0, 1e-6,NULL, 0,0);
89 printf("%d minf=%g at A=%g, w=%g, G=%g\n", count, minf, p[0],p[1],p[2]);
92 nlopt_minimize(NLOPT_LN_NELDERMEAD, 3, lorentzerr, &d,
94 -HUGE_VAL, 0,0, 1e-6,NULL, 0,0);
96 printf("%d minf=%g at A=%g, w=%g, G=%g\n", count, minf, p[0],p[1],p[2]);
99 nlopt_minimize(NLOPT_LN_SBPLX, 3, lorentzerr, &d,
101 -HUGE_VAL, 0,0, 1e-6,NULL, 0,0);
103 printf("%d minf=%g at A=%g, w=%g, G=%g\n", count, minf, p[0],p[1],p[2]);