性能较好的随机数发生器

       产生随机数的最简单的方法是线性同余数发生器,它于1951年由Lehmer首先提出,数x1,x2,... 的生成满足:
                                          xi+1 = Axi mod M
       为了开始这个序列,必须给出x0的某个值,这个值叫做种子(seed)。

static   const   int  A  =   48271 ;
static   const   int  M  =   2147483647 ;
static   const   int  Q  =  M  /  A;
static   const   int  R  =  M  %  A;

class  Random
{
    
public:
        
explicit Random( int initialValue = 1 );

        
int randomInt();
        
double random0_1();
        
int randomInt( int low, int high);

    
private:
       
int state;
}
;

/**
 * Construct with initialValue for the state.
 
*/

Random::Random( 
int  initialValue)
{
      
if( initialValue < 0)
          initialValue 
+= M;
      state 
= initialValue;
      
if( state == 0)
          state 
= 1;
}


/**
 *Return a pseudorandom int, and change the internal state.
 
*/

int  Random::randomInt()
{
    
int tmpState = A * ( state % Q ) - R * (state / Q );

    
if( tmpState >= 0)
        state 
= tmpState;
    
else
        state 
= tmpState + M;
    
return state;
}


/**
 * Return a pseudorandom double in the open range 0..1
 * and change the internal state.
 
*/

double  Random::random0_1( )
{
    
return (double) randomInt( ) / M;
}


/**
 * Return an int in the closed range [low,high], and
 * change the internal state.
 
*/

int  Random::randomInt(  int  low,  int  high )
{
    
double partitionSize = (double) M / ( high - low + 1 );

    
return (int) ( randomInt( ) / partitionSize ) + low;
}

你可能感兴趣的:(性能较好的随机数发生器)