Object-oriented Scientific Computing Library: Version 0.910
Monte Carlo Integration

Monte Carlo integration is performed by descendants of mcarlo_inte (gsl_monte, gsl_miser, and gsl_vegas). These routines are generally superior to the direct methods for integrals over regions with large numbers of spatial dimensions.

Monte Carlo Integration Example

This example computes the integral

\[ \int_0^{\pi} \int_0^{\pi} \int_0^{\pi} \frac{1}{\pi^3} \left(1-\cos x \cos y \cos z\right)^{-1} \]

and compares the result with the exact value, 1.3932039296.

/* Example: ex_minte.cpp
   -------------------------------------------------------------------
   An example to demonstrate multidimensional integration
*/

#include <o2scl/test_mgr.h>
#include <o2scl/multi_funct.h>
#include <o2scl/composite_inte.h>
#include <o2scl/gsl_inte_qng.h>
#include <o2scl/gsl_vegas.h>

/// For M_PI
#include <gsl/gsl_math.h>

using namespace std;
using namespace o2scl;

double test_fun(size_t nv, const ovector_base &x) {
  double y=1.0/(1.0-cos(x[0])*cos(x[1])*cos(x[2]))/M_PI/M_PI/M_PI;
  return y;
}

int main(void) {
  test_mgr t;
  t.set_output_level(1);
 
  cout.setf(ios::scientific);

  double exact=1.3932039296;
  double res;

  double err;

  gsl_vegas<multi_funct<> > gm;
  ovector a(3), b(3);
  a.set_all(0.0);
  b.set_all(M_PI);

  multi_funct_fptr<> tf(test_fun);

  gm.n_points=100000;
  gm.minteg_err(tf,3,a,b,res,err);

  cout << res << " " << exact << " " << (res-exact)/err << endl;
  t.test_rel(res,exact,err*10.0,"O2scl");

  t.report();
 
  return 0;
}
// End of example

 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines

Documentation generated with Doxygen. Provided under the GNU Free Documentation License (see License Information).

Get Object-oriented Scientific Computing
Lib at SourceForge.net. Fast, secure and Free Open Source software
downloads.