一个简单的随机数生成算法实现(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#的顶下先 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zeloas

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值