Random.h

Go to the documentation of this file.
00001 // ---------------------------------------------------------------------
00002 // $Id: Random.h 156 2008-06-08 07:13:49Z daaugusto $
00003 //
00004 //   Random.h (created on Tue Nov 08 01:08:35 BRT 2005)
00005 // 
00006 //   Genetic Algorithm File Fitter (gaffitter)
00007 //
00008 //   Copyright (C) 2005-2008 Douglas A. Augusto
00009 // 
00010 // This file is part of gaffitter.
00011 // 
00012 // gaffitter is free software; you can redistribute it and/or modify it
00013 // under the terms of the GNU General Public License as published by the
00014 // Free Software Foundation; either version 3 of the License, or (at
00015 // your option) any later version.
00016 // 
00017 // gaffitter is distributed in the hope that it will be useful, but
00018 // WITHOUT ANY WARRANTY; without even the implied warranty of
00019 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00020 // General Public License for more details.
00021 // 
00022 // You should have received a copy of the GNU General Public License
00023 // along with gaffitter; if not, see <http://www.gnu.org/licenses/>.
00024 //
00025 // ---------------------------------------------------------------------
00026 
00027 #ifndef random_hh
00028 #define random_hh
00029 
00030 #include <cstdlib>
00031 #include <cmath>
00032 #include <ctime>
00033 
00034 // ---------------------------------------------------------------------
00038 class Random {
00039 public:
00041    static unsigned long Seed(unsigned long seed = 0L) 
00042    { 
00043       srand(seed = (seed == 0L) ? time(NULL) : seed);
00044       return seed;
00045    }
00046 
00048    static unsigned long Int() { return rand(); }
00049 
00051    static long Int(long a, long b)
00052    {
00053       return a + static_cast<long>( Int()*(b-a+1.0) / (RAND_MAX+1.0) );
00054    }    
00055 
00057    static double Real(double a=0.0, double b=1.0)
00058    {
00059       return a + Int()*(b-a) / RAND_MAX;
00060    }
00061 
00062    /* Non Uniform Random Numbers
00063     *
00064     * 'weight = 1': uniform distribution between 'a' and 'b' [a,b]
00065     * 'weight > 1': non uniform distribution towards 'a'
00066     * 'weight < 1': non uniform distribution towards 'b'
00067     */
00068 
00070    static long NonUniformInt(double weight, long a, long b)
00071    {
00072       return static_cast<long>(pow(Real(0.0, 1.0), weight) * (b-a) + a);
00073    }
00074 
00076    static double NonUniformReal(double weight, double a=0.0, double b=1.0)
00077    {
00078       return pow(Real(0.0, 1.0), weight) * (b-a) + a;
00079    }
00080 
00082    static bool Probability(double p)
00083    {
00084       if (p <= 0.0) return false;
00085       if (p >= 1.0) return true;
00086 
00087       return (Real(0.0,1.0) < p) ? true : false;
00088    }
00089 };
00090 
00091 // --------------------------------------------------------------------
00092 
00093 #endif