chiark / gitweb /
0936ae1093630ce6895fc29c950767c17425b010
[nlopt.git] / util / sobolseq_test.c
1 /* Copyright (c) 2007 Massachusetts Institute of Technology
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining
4  * a copy of this software and associated documentation files (the
5  * "Software"), to deal in the Software without restriction, including
6  * without limitation the rights to use, copy, modify, merge, publish,
7  * distribute, sublicense, and/or sell copies of the Software, and to
8  * permit persons to whom the Software is furnished to do so, subject to
9  * the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be
12  * included in all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21  */
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <math.h>
26 #include <time.h>
27 #include "nlopt-util.h"
28
29 #define MAXDIM 1111
30
31 /* test integrand from Joe and Kuo paper ... integrates to 1 */
32 static double testfunc(unsigned n, const double *x)
33 {
34     double f = 1;
35     unsigned j;
36     for (j = 1; j <= n; ++j) {
37         double cj = pow((double) j, 0.3333333333333333333);
38         f *= (fabs(4*x[j-1] - 2) + cj) / (1 + cj);
39     }
40     return f;
41 }
42
43 int main(int argc, char **argv)
44 {
45     unsigned n, j, i, sdim;
46     static double x[MAXDIM];
47     double testint_sobol = 0, testint_rand = 0;
48     nlopt_sobol s;
49     if (argc < 3) {
50         fprintf(stderr, "Usage: %s <sdim> <ngen>\n", argv[0]);
51         return 1;
52     }
53     nlopt_init_genrand(time(NULL));
54     sdim = atoi(argv[1]);
55     s = nlopt_sobol_create(sdim);
56     n = atoi(argv[2]);
57     nlopt_sobol_skip(s, n, x);
58     for (j = 1; j <= n; ++j) {
59         nlopt_sobol_next01(s, x);
60         testint_sobol += testfunc(sdim, x);
61         if (j < 100) {
62             printf("x[%u]: %g", j, x[0]);
63             for (i = 1; i < sdim; ++i) printf(", %g", x[i]);
64             printf("\n");
65         }
66         for (i = 0; i < sdim; ++i) x[i] = nlopt_urand(0.,1.);
67         testint_rand += testfunc(sdim, x);
68     }
69     nlopt_sobol_destroy(s);
70     printf("Test integral = %g using Sobol, %g using pseudorandom.\n",
71         testint_sobol / n, testint_rand / n);
72     printf("        error = %g using Sobol, %g using pseudorandom.\n",
73         testint_sobol / n - 1, testint_rand / n - 1);
74     return 0;
75 }