📄 mrand.cpp
字号:
// $common\mrand.cpp 1.5 milbo$// Warning: this is raw research code -- expect it to be quite messy.//// Rand returns an int between 0 and n-1// RandDouble returns a double between 0 and n-1// And so on// These routines are based on "Numerical Recipes in C" 2nd edition ran1().//// milbo oct 2002#include "all.hpp"static const int N_GENERATORS = 10;static iGenerator[N_GENERATORS];static long iRand[N_GENERATORS];static double Ran1(long *piRand);//-----------------------------------------------------------------------------void SeedRand (int iSeed, int iGenerator){ASSERT(iGenerator < N_GENERATORS);if (iSeed > 0) iSeed = -iSeed; // have to init with a negative numberiRand[iGenerator] = iSeed;}//-----------------------------------------------------------------------------// returns an integer in the range 0 to n-1int Rand (int n, int iGenerator){ASSERT(iGenerator < N_GENERATORS);return (int)(n * Ran1(&iRand[iGenerator]));}//-----------------------------------------------------------------------------// returns an integer in the range -n to to n-1int RandAboutZero (int n, int iGenerator){ASSERT(iGenerator < N_GENERATORS);return (int)(2 * n * Ran1(&iRand[iGenerator]) - n);}//-----------------------------------------------------------------------------// returns a double random number between 0 to n-EPSdouble RandDouble (double n, int iGenerator){ASSERT(iGenerator < N_GENERATORS);return n * Ran1(&iRand[iGenerator]);}//-----------------------------------------------------------------------------// Returns a gaussian random number with the given standard deviation//// We use the fact that the sum of uniformly distibuted random variables// approximates a gaussian distribution (by the central limit theorem)double RandGauss (double StdDev, int iGenerator){if (StdDev == 0) // for efficiency return 0;ASSERT(iGenerator < N_GENERATORS);double r = 0;for (int i = 0; i < 12; i++) r += RandDouble(2, iGenerator) - 1; // add a random number between -1 and +1return (StdDev * r) / 2;}//-----------------------------------------------------------------------------// Return a random number between 0.0 and 1.0 exclustive of the endpoint values// Lifted from "Numerical Recipes in C" 2nd edition ran1()#define IA 16807#define IM 2147483647#define AM (1.0/IM)#define IQ 127773#define IR 2836#define NTAB 32#define NDIV (1+(IM-1)/NTAB)#define EPS 1.2e-7#define RNMX (1.0-EPS)static double Ran1 (long *piRand){int j;long k;static long iy=0;static long iv[NTAB];double temp;if (*piRand <= 0 || !iy) { if (-*piRand < 1) *piRand=1; else *piRand = -*piRand; for (j=NTAB+7;j>=0;j--) { k=*piRand/IQ; *piRand=IA*(*piRand-k*IQ)-IR*k; if (*piRand < 0) *piRand += IM; if (j < NTAB) iv[j] = *piRand; } iy=iv[0]; }k=*piRand/IQ;*piRand=IA*(*piRand-k*IQ)-IR*k;if (*piRand < 0) *piRand += IM;j=iy/NDIV;iy=iv[j];iv[j] = *piRand;if ((temp=(AM*iy)) > RNMX) return RNMX;else return temp;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -