C++学习笔记-随机数

随机函数Rand SRand

原理

计算机常用线性同余法产生随机数,LCG( Linear Congruential Generator)用递推的方法求随机序列

X(n+1)=(ax(n)+c)%M

其中: 0<=a<M,0<=c<M,0<=x(0)<M. 为了计算迅速,M一般取2的幂,求余可用移位实现。
为了尽可能让序列周期长,最大为M,a和c一般互斥,与M也互斥。

周期为M的充分必要条件:

T(k)T(k)%MT(k)%M=(xak+(a(k1)c)+(a(k2)c)+...+ac+c=x(k=M)x(0<k<M)

只要证明x=0~M-1中任意一个上式成立即可。很容易推断只要有一个x周期为M,那么其他所有x周期也为M,序列周期为M。
由x=0和x=1容易推出充分条件: aM%M=1 . a和M必然互斥(反正法).
必要条件:TODO

C++函数

C++标准库里有两个随机函数,一个设置随机种子 x(0),一个产生伪随机数。

int Rand(void)

产生随机函数,使用的seed是上一次调用SRand时指定的seed

void srand (unsigned int seed)

Initialize random number generator
The pseudo-random number generator is initialized using the argument passed as seed.

For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.

Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.

If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.

In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header ). This is distinctive enough for most trivial randomization needs.

Ref:http://www.cplusplus.com/reference/cstdlib/srand/

使用的时候先指定随机种子srand(time(NULL)),再调用rand().rand()里会将这一次得到的随机数作为下一次的种子。
程序每次启动,计算机自己初始化的种子相同,得到的随机序列也相同。主要目的为了方便调试。因此想得到真正的随机序列,自己初始化一下种子。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值