analistica/misc/pdfs.c

59 lines
2.2 KiB
C
Raw Normal View History

2020-03-06 02:24:32 +01:00
// This program generates a collection of random numbers which follow the
// distribution whose name is given in input by the user when calling the
// program and outputs an histogram of the result. Maximum and minimum of
// the range must also be given. The random number distribution functions
// are taken from the GSL library at:
// https://www.gnu.org/software/gsl/doc/html/randist.html
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_histogram.h>
int main (int argc, char** argv)
{
// An histogram with 100 bins which range from 0 to 100 is set:
size_t bins = 100;
int low = atoi(argv[2]);
int upp = atoi(argv[3]);
gsl_histogram * histo = gsl_histogram_alloc(bins);
gsl_histogram_set_ranges_uniform(histo, low, upp);
// The random number generator is set:
gsl_rng* gen = gsl_rng_alloc(gsl_rng_taus);
// 100'000 random numbers are generated and put into the histogram:
size_t N = 100000;
for (size_t i = 0; i < N; i++)
{
if (strcmp(argv[1], "binomial") == 0)
gsl_histogram_increment(histo, gsl_ran_binomial(gen, 0.3, 10));
if (strcmp(argv[1], "poisson") == 0)
gsl_histogram_increment(histo, gsl_ran_poisson(gen, 1));
if (strcmp(argv[1], "uniform") == 0)
gsl_histogram_increment(histo, gsl_rng_get(gen)*100);
if (strcmp(argv[1], "gaussian") == 0)
gsl_histogram_increment(histo, gsl_ran_gaussian(gen, 5)+30);
if (strcmp(argv[1], "wigner") == 0)
gsl_histogram_increment(histo, gsl_ran_cauchy(gen, 10)+20);
if (strcmp(argv[1], "landau") == 0)
gsl_histogram_increment(histo, gsl_ran_landau(gen));
if (strcmp(argv[1], "chi2") == 0)
gsl_histogram_increment(histo, gsl_ran_gamma(gen, 5, 2));
if (strcmp(argv[1], "exponential") == 0)
gsl_histogram_increment(histo, gsl_ran_exponential(gen, 5));
if (strcmp(argv[1], "student") == 0)
gsl_histogram_increment(histo, gsl_ran_tdist(gen, 3));
if (strcmp(argv[1], "fischer") == 0)
gsl_histogram_increment(histo, gsl_ran_fdist(gen, 3, 4));
}
// The histogram is given in output:
gsl_histogram_fprintf (stdout, histo, "%g", "%g");
// The memory is freed.
gsl_rng_free(gen);
gsl_histogram_free(histo);
return 0;
}