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

Revision 2, 1.6 KB checked in by pchapin, 8 years ago (diff)

Reformatted the comments in the existing source files.

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