Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
| Download
Project: Testing 18.04
Path: test.c
Views: 985#include <stdlib.h>1#include <gsl/gsl_math.h>2#include <gsl/gsl_monte.h>3#include <gsl/gsl_monte_miser.h>4#include <gsl/gsl_monte_plain.h>5#include <gsl/gsl_monte_vegas.h>67/* Computation of the integral,89I = int (dx dy dz)/(2pi)^3 1/(1-cos(x)cos(y)cos(z))1011over (-pi,-pi,-pi) to (+pi, +pi, +pi). The exact answer12is Gamma(1/4)^4/(4 pi^3). This example is taken from13C.Itzykson, J.M.Drouffe, "Statistical Field Theory -14Volume 1", Section 1.1, p21, which cites the original15paper M.L.Glasser, I.J.Zucker, Proc.Natl.Acad.Sci.USA 74161800 (1977) */1718/* For simplicity we compute the integral over the region19(0,0,0) -> (pi,pi,pi) and multiply by 8 */2021double exact = 1.3932039296856768591842462603255;2223double g(double *k, size_t dim, void *params) {24(void)(dim); /* avoid unused parameter warnings */25(void)(params);26double A = 1.0 / (M_PI * M_PI * M_PI);27return A / (1.0 - cos(k[0]) * cos(k[1]) * cos(k[2]));28}2930void display_results(char *title, double result, double error) {31printf("%s ==================\n", title);32printf("result = % .6f\n", result);33printf("sigma = % .6f\n", error);34printf("exact = % .6f\n", exact);35printf("error = % .6f = %.2g sigma\n", result - exact,36fabs(result - exact) / error);37}3839int main(void) {40double res, err;4142double xl[3] = {0, 0, 0};43double xu[3] = {M_PI, M_PI, M_PI};4445const gsl_rng_type *T;46gsl_rng *r;4748gsl_monte_function G = {&g, 3, 0};4950size_t calls = 500000;5152gsl_rng_env_setup();5354T = gsl_rng_default;55r = gsl_rng_alloc(T);5657{58gsl_monte_plain_state *s = gsl_monte_plain_alloc(3);59gsl_monte_plain_integrate(&G, xl, xu, 3, calls, r, s, &res, &err);60gsl_monte_plain_free(s);6162display_results("plain", res, err);63}6465{66gsl_monte_miser_state *s = gsl_monte_miser_alloc(3);67gsl_monte_miser_integrate(&G, xl, xu, 3, calls, r, s, &res, &err);68gsl_monte_miser_free(s);6970display_results("miser", res, err);71}7273{74gsl_monte_vegas_state *s = gsl_monte_vegas_alloc(3);75gsl_monte_vegas_integrate(&G, xl, xu, 3, 10000, r, s, &res, &err);76display_results("vegas warm-up", res, err);7778printf("converging...\n");7980do {81gsl_monte_vegas_integrate(&G, xl, xu, 3, calls / 5, r, s, &res, &err);82printf(83"result = % .6f sigma = % .6f "84"chisq/dof = %.1f\n",85res, err, gsl_monte_vegas_chisq(s));86} while (fabs(gsl_monte_vegas_chisq(s) - 1.0) > 0.5);8788display_results("vegas final", res, err);8990gsl_monte_vegas_free(s);91}9293gsl_rng_free(r);9495return 0;96}979899