source: trunk/c++_tools/random/random.cc @ 575

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

Corrected copyright statement.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 2.0 KB
Line 
1// $Id: random.cc 562 2006-03-15 09:19:51Z jari $
2
3/*
4  Copyright (C) 2005, 2006 Jari Häkkinen, Peter Johansson
5
6  This file is part of the thep c++ tools library,
7                                http://lev.thep.lu.se/trac/c++_tools
8
9  The c++ tools library is free software; you can redistribute it
10  and/or modify it under the terms of the GNU General Public License
11  as published by the Free Software Foundation; either version 2 of
12  the License, or (at your option) any later version.
13
14  The c++ tools library is distributed in the hope that it will be
15  useful, but WITHOUT ANY WARRANTY; without even the implied warranty
16  of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  General Public License for more details.
18
19  You should have received a copy of the GNU General Public License
20  along with this program; if not, write to the Free Software
21  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
22  02111-1307, USA.
23*/
24
25#include <c++_tools/random/random.h>
26#include <c++_tools/statistics/Histogram.h>
27
28#include <fstream>
29#include <iostream>
30
31
32namespace theplu {
33namespace random {
34
35
36  RNG* RNG::instance_ = NULL;
37
38
39  RNG::RNG(void)
40  {
41    gsl_rng_env_setup();  // support rng/seed changes through environment vars
42    rng_ = gsl_rng_alloc(gsl_rng_default);  // Memory is allocated here!
43  }
44
45
46
47  RNG::~RNG(void)
48  {
49    gsl_rng_free(rng_);
50    rng_=NULL;
51    delete instance_;
52  }
53
54
55
56  u_long RNG::seed_from_devurandom(void)
57  {
58    u_char ulongsize=sizeof(u_long);
59    char* buffer=new char[ulongsize];
60    std::ifstream is("/dev/urandom");
61    is.read(buffer,ulongsize);
62    is.close();
63    u_long s=0;
64    for (u_int i=0; i<ulongsize; i++) {
65      u_char ch=buffer[i];
66      s+=ch<<((ulongsize-1-i)*8);
67    }
68    seed(s);
69    return s;
70  }
71
72
73
74  DiscreteGeneral::DiscreteGeneral(const statistics::Histogram& hist)
75  {
76    double* p = new double[ hist.nof_bins() ];
77    for (size_t i=0; i<hist.nof_bins(); i++) 
78      p[ i ] = hist[i];
79    gen_ = gsl_ran_discrete_preproc( hist.nof_bins(), p );
80    delete p;
81  }
82
83
84
85  DiscreteGeneral::~DiscreteGeneral(void)
86  {
87    if (gen_)
88      gsl_ran_discrete_free( gen_ );
89    gen_ = NULL;
90  }
91
92
93}} // of namespace random and namespace theplu
Note: See TracBrowser for help on using the repository browser.