Alex Bikfalvi
SimStream Documentation
Rand.cpp
00001 #include "Headers.h" 00002 #include "Rand.h" 00003 00004 __uint32 CRand::Init() 00005 { 00006 #if !defined(DETRAND) 00007 __uint32 seed = (__uint32)time(NULL); 00008 srand(seed); 00009 #endif 00010 return 0; 00011 } 00012 00013 double CRand::Generate() 00014 { 00015 #if !defined(DETRAND) && defined(_WINDOWS) 00016 __uint32 rvalue; 00017 rand_s(&rvalue); 00018 return ((double)rvalue) / UINT_MAX; 00019 #else 00020 #if RAND_MAX == 0x7FFF 00021 return ((double)rand()*rand()) / ((double)RAND_MAX*RAND_MAX); 00022 #else 00023 return ((double)rand()) / ((double)RAND_MAX); 00024 #endif 00025 #endif 00026 } 00027 00028 __uint32 CRand::Generate(__uint32 max) 00029 { 00030 #if !defined(DETRAND) && defined(_WINDOWS) 00031 __uint32 rvalue; 00032 rand_s(&rvalue); 00033 return (__uint32)(max * (((double)rvalue) / UINT_MAX)); 00034 #else 00035 #if RAND_MAX == 0x7FFF 00036 return (__uint32)(max * ((double)rand()*rand() / (RAND_MAX*RAND_MAX))); 00037 #else 00038 return (__uint32)(max * ((double)rand() / RAND_MAX)); 00039 #endif 00040 #endif 00041 } 00042 00043 __uint32 CRand::GenerateUInt32() 00044 { 00045 #if !defined(DETRAND) && defined(_WINDOWS) 00046 __uint32 rnd; 00047 rand_s(&rnd); 00048 return rnd; 00049 #else 00050 #if RAND_MAX == 0x7FFF 00051 return (((__uint32)rand()) << 17) | (((__uint32)rand()) << 2) | (((__uint32)rand()) & 0x3); 00052 #else 00053 return (((__uint32)rand()) << 1) | (((__uint32)rand()) & 0x1); 00054 #endif 00055 #endif 00056 }
Last updated: February 8, 2011