/home/pxiang/workspace_new/CalculateGreenFunction/src/Utility/random_generator.h

Go to the documentation of this file.
00001 /*
00002  * random_generator.h
00003  *
00004  *  Created on: Dec 17, 2013
00005  *      Author: pxiang
00006  */
00007 
00008 #ifndef RANDOM_GENERATOR_H_
00009 #define RANDOM_GENERATOR_H_
00010 
00011 #include "types.h"
00012 
00013 class RandomNumberGenerator {
00014         private:
00015                 unsigned seed;
00016 
00017         public:
00018 
00019 
00020 // constructor
00021         RandomNumberGenerator(unsigned inputSeed) {
00022                 seed = inputSeed;
00023                 srand(seed);
00024         }
00025 
00026         // default constructor
00027         RandomNumberGenerator() {
00028                 //use the current time as seed for random numbers
00029                 seed = (unsigned)time(NULL);
00030                 srand(seed);
00031         }
00032 
00033         void SetSeed(unsigned inputSeed) {
00034                 seed = inputSeed;
00035                 srand(seed);
00036         }
00037 
00038 // produce a complex random number in [0, 1) + [0, 1)*I given the seed
00039         dcomplex randomComplex() {
00040                 double randomReal = (double)rand()/(double)RAND_MAX;
00041                 double randomImag = (double)rand()/(double)RAND_MAX;
00042                 dcomplex rc = dcomplex(randomReal,randomImag);
00043                 return rc;
00044         }
00045 
00046         // produce a complex random number in [0, 1) + [0, 1)*I given the seed
00047         double randomReal() {
00048                 double random = (double)rand()/(double)RAND_MAX;
00049                 return random;
00050         }
00051 
00052 
00053 };
00054 
00055 // generate a matrix of given dimension whose elements are random numbers in [0, 1)
00056 class RandomNumberMatrix {
00057 public:
00058         RandomNumberMatrix(int row_count, int col_count, unsigned seed) {
00059                 rows = row_count;
00060                 cols = col_count;
00061                 m.resize(rows, cols);
00062                 rng.SetSeed(seed);
00063                 for (int i=0; i<rows; i++) {
00064                         for (int j=0; j<cols; ++j) {
00065                                 m(i, j) = rng.randomReal();
00066                         }
00067                 }
00068         }
00069 
00070         double operator()(const int r, const int c) const {
00071                 return m(r, c);
00072         }
00073 
00074 
00075         ~RandomNumberMatrix() {
00076                 m.resize(0, 0);
00077                 rows = 0;
00078                 cols = 0;
00079         }
00080 
00081 private:
00082         DMatrix m;
00083         int rows;
00084         int cols;
00085         RandomNumberGenerator rng;
00086 };
00087 
00088 
00089 
00090 #endif

Generated on Fri Oct 31 16:58:45 2014 for CalculateGreenFunction by  doxygen 1.4.7