一個簡單的隨機數生成算法實現(C++)

#ifndef EASYRANDOM_INCLUDED
#define    EASYRANDOM_INCLUDED

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 initialVal=1);

    
int RandomInt();
    
double Random0_1();
    
int RandomInt(int low,int high);
private :
    
int state;
}
;

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


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

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

    
return state;
}

//生成0.0到1.0之間的隨機小數
double Random::Random0_1()
{
    
return (double)RandomInt()/M;
}

//生成low到high之間的隨機整數
int Random::RandomInt(int low, int high)
{
    
int range = high - low;
    
    
return low+RandomInt()%range;
}


#endif

這些數的生成依賴於算法,不能算是真正的隨機數,只能算是僞隨機數。本例中的算法詳情google 線性同餘生成器。

ps.

沒有關鍵的C代碼插入方式,用C#的頂下先 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章