source: trunk/lib/random/Random.cc @ 374

Last change on this file since 374 was 374, checked in by Jari Häkkinen, 18 years ago

Added documentation.
Added missing Makefile.am.
Implemented seeding of the rng. Implemented seed acquring from /dev/urandom.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 1.3 KB
Line 
1// $Id: Random.cc 374 2005-08-05 22:30:57Z jari $
2
3#include <c++_tools/random/Random.h>
4#include <c++_tools/statistics/Histogram.h>
5
6#include <fstream>
7#include <iostream>
8
9
10namespace theplu {
11namespace random {
12
13
14  RNG* RNG::instance_ = NULL;
15
16
17  RNG::RNG(u_long s)
18  {
19    gsl_rng_env_setup();  // support rng/seed changes through environment vars
20    rng_ = gsl_rng_alloc(gsl_rng_default);  // Memory is allocated here!
21    seed(s);
22  }
23
24
25
26  RNG::~RNG(void)
27  {
28    gsl_rng_free(rng_);
29    rng_=NULL;
30    delete instance_;
31  }
32
33
34
35  RNG* RNG::instance(u_long seed)
36  {
37    if (!instance_)
38      instance_ = new RNG(seed);
39    return instance_;
40  }
41
42
43
44  u_long RNG::seed_from_devurandom(void)
45  {
46    u_char ulongsize=sizeof(u_long);
47    char* buffer=new char[ulongsize];
48    std::ifstream is("/dev/urandom");
49    is.read(buffer,ulongsize);
50    is.close();
51    u_long s=0;
52    for (u_int i=0; i<ulongsize; i++) {
53      u_char ch=buffer[i];
54      s+=ch<<((ulongsize-1-i)*8);
55    }
56    seed(s);
57    return s;
58  }
59
60
61
62  DiscreteGeneral::DiscreteGeneral(const statistics::Histogram& hist)
63  {
64    double* p = new double[ hist.nof_bins() ];
65    for (size_t i=0; i<hist.nof_bins(); i++) 
66      p[ i ] = hist[i];
67    gen_ = gsl_ran_discrete_preproc( hist.nof_bins(), p );
68    delete p;
69  }
70
71
72
73  DiscreteGeneral::~DiscreteGeneral(void)
74  {
75    if (gen_)
76      gsl_ran_discrete_free( gen_ );
77    gen_ = NULL;
78  }
79
80
81}} // of namespace random and namespace theplu
Note: See TracBrowser for help on using the repository browser.