randomgenerator.cpp
1 /********************************************************************************
2  * FARSA Genetic Algorithm Library *
3  * Copyright (C) 2007-2008 Gianluca Massera <emmegian@yahoo.it> *
4  * *
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 2 of the License, or *
8  * (at your option) any later version. *
9  * *
10  * This program is distributed in the hope that it will be useful, *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13  * GNU General Public License for more details. *
14  * *
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 St, Fifth Floor, Boston, MA 02110-1301 USA *
18  ********************************************************************************/
19 
20 #include "randomgenerator.h"
21 #include <cmath>
22 
23 #ifdef FARSA_USE_GSL
24  #include "gsl/gsl_rng.h"
25  #include "gsl/gsl_randist.h"
26 #endif
27 
28 namespace farsa {
29 
30 class FARSA_UTIL_INTERNAL RandomGeneratorPrivate {
31 public:
32 #ifdef FARSA_USE_GSL
33  gsl_rng* rng;
35  rng = gsl_rng_alloc( gsl_rng_taus2 );
36  };
38  gsl_rng_free( rng );
39  };
40 #endif
41 };
42 
44  prive = new RandomGeneratorPrivate();
45 #ifdef FARSA_USE_GSL
46  gsl_rng_set( prive->rng, seed );
47 #endif
48 }
49 
51  delete prive;
52 }
53 
54 void RandomGenerator::setSeed( int seed ) {
55  this->seedv = seed;
56 #ifdef FARSA_USE_GSL
57  gsl_rng_set( prive->rng, seed );
58 #endif
59 }
60 
62  return seedv;
63 }
64 
65 bool RandomGenerator::getBool( double trueProbability ) {
66 #ifdef FARSA_USE_GSL
67  return ( gsl_rng_uniform( prive->rng ) < trueProbability );
68 #endif
69 }
70 
71 int RandomGenerator::getInt( int min, int max ) {
72 #ifdef FARSA_USE_GSL
73  return ( gsl_rng_uniform_int( prive->rng, qAbs( max-min )+1 ) + min );
74 #endif
75 }
76 
77 double RandomGenerator::getDouble( double min, double max ) {
78 #ifdef FARSA_USE_GSL
79  //--- FIXME this implementation never return max
80  return gsl_ran_flat( prive->rng, min, max );
81 #endif
82 }
83 
84 double RandomGenerator::getGaussian( double var, double mean ) {
85 #ifdef FARSA_USE_GSL
86  return gsl_ran_gaussian( prive->rng, var ) + mean;
87 #endif
88 }
89 
90 } // end namespace farsa