source: Project Repository/src/random.cpp @ 1

Revision 1, 2.0 KB checked in by pchapin, 8 years ago (diff)

Added the HWRNG project.

Line 
1/****************************************************************************
2FILE          : random.cpp
3LAST REVISION : 2005-11-21
4SUBJECT       : Implementation of random number abstract class.
5PROGRAMMER    : (C) Copyright 2005 by Peter C. Chapin
6
7This file contains the implementation of the non-inline member functions of
8the various random number classes.
9
10Please send comments or bug reports to
11
12     Peter C. Chapin
13     Electrical and Computer Engineering Technology
14     Vermont Technical College
15     Randolph Center, VT 05061
16     pchapin@ecet.vtc.edu
17****************************************************************************/
18
19#include <ctime>
20#include <limits>
21#include "random.h"
22
23namespace rnd {
24
25  // This method will return non-random results if the underlying
26  // generator has a maximum value that is not near a power of two.
27  // Ideally it should be a power of two minus 1. Otherwise when the
28  // mask reaches the most significant bit, it will see an excessive
29  // number of zero bits there.
30  //
31  unsigned bit_random::next()
32  {
33    unsigned bit;
34
35    // Generate a fresh number if necessary.
36    if (mask == 0) {
37      current = generator.next();
38      mask = 0x1;
39    }
40
41    // Examine the current bit in the number.
42    bit = (current & mask) ? 1 : 0;
43
44    // Advance the mask, taking care not to overflow unsigned or go off
45    // the end of the values coming back from the underlying generator.
46    //
47    if (mask > (std::numeric_limits<unsigned>().max() >> 1)) {
48      mask = 0;
49    }
50    else {
51      mask <<= 1;
52      if (mask > generator.max()) mask = 0;
53    }
54    return bit;
55  }
56
57
58  // This implementation uses the output of std::time to seed the random
59  // number generator. There are numerous problems with doing this, but
60  // some applications are not concerned by them.
61  //
62  void seeded_random::time_seed()
63  {
64    std::time_t raw = std::time(0);
65    seed(static_cast<unsigned>(raw));
66  }
67
68}
Note: See TracBrowser for help on using the repository browser.