您的位置:首页 > 编程语言 > C语言/C++

一个简单的随机数生成算法实现(C++)

2008-04-14 16:22 573 查看

#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#的顶下先
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: