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

本文介绍了一个基于C++实现的简单伪随机数生成器,该生成器使用线性同余方法生成随机数。提供了生成指定范围内的随机整数及0到1之间的随机浮点数的功能。
#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#的顶下先 

posted on 2008-04-14 16:22 secularbird 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/zelos/archive/2008/04/14/3402884.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值