analistica/ex-5/casino.c

38 lines
851 B
C
Raw Normal View History

2020-03-06 02:24:32 +01:00
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
int main(int argc, char** argv){
size_t size = atoi(argv[1]); // size of the generated sample
// Initialize an RNG.
gsl_rng_env_setup();
gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
// Random points (x, y) generation: x in [0,1), y in [0,3)
// get if y < exp(x)
// leave if y > exp(x)
size_t in = 0;
size_t total = 0;
do{
double x = gsl_rng_uniform(r);
double y = 3 * gsl_rng_uniform(r);
if (y <= exp(x)){
in++;
}
total++;
} while (total < size);
// The integral is esitmated thorugh the proportion:
// integral : 3 = in : total
double integral = 3.0*(double)in/(double)total;
printf("∫exp(x)dx in [0,1]:\t%.07f\n", integral);
// Free memory
gsl_rng_free(r);
return EXIT_SUCCESS;
}