3 * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 /* Plain Monte-Carlo. */
26 #include <gsl/gsl_math.h>
27 #include <gsl/gsl_rng.h>
28 #include <gsl/gsl_monte_plain.h>
31 gsl_monte_plain_integrate (const gsl_monte_function * f,
32 const double xl[], const double xu[],
36 gsl_monte_plain_state * state,
37 double *result, double *abserr)
39 double vol, m = 0, q = 0;
43 if (dim != state->dim)
45 GSL_ERROR ("number of dimensions must match allocated size", GSL_EINVAL);
48 for (i = 0; i < dim; i++)
52 GSL_ERROR ("xu must be greater than xl", GSL_EINVAL);
55 if (xu[i] - xl[i] > GSL_DBL_MAX)
57 GSL_ERROR ("Range of integration is too large, please rescale",
62 /* Compute the volume of the region */
66 for (i = 0; i < dim; i++)
71 for (n = 0; n < calls; n++)
73 /* Choose a random point in the integration region */
75 for (i = 0; i < dim; i++)
77 x[i] = xl[i] + gsl_rng_uniform_pos (r) * (xu[i] - xl[i]);
81 double fval = GSL_MONTE_FN_EVAL (f, x);
83 /* recurrence for mean and variance */
87 q += d * d * (n / (n + 1.0));
99 *abserr = vol * sqrt (q / (calls * (calls - 1.0)));
105 gsl_monte_plain_state *
106 gsl_monte_plain_alloc (size_t dim)
108 gsl_monte_plain_state *s =
109 (gsl_monte_plain_state *) malloc (sizeof (gsl_monte_plain_state));
113 GSL_ERROR_VAL ("failed to allocate space for state struct",
117 s->x = (double *) malloc (dim * sizeof (double));
122 GSL_ERROR_VAL ("failed to allocate space for working vector",
131 /* Set some default values and whatever */
134 gsl_monte_plain_init (gsl_monte_plain_state * s)
138 for (i = 0; i < s->dim; i++)
147 gsl_monte_plain_free (gsl_monte_plain_state * s)