C++: 详解 使用Schrage's Method Revealed 实现随机化算法

C++: 详解 使用Schrage’s Method Revealed(随机化算法)

标签: C++ 随机化算法 Schrage

by 小威威


在了解Schrage’s Method Revealed(随机化算法)之前,我们先来了解C++中随机数必备的基础知识。

1.随机数

在C++中,随机数的产生是依靠某种方法实现的,因为在计算机上无法实现随机数真正的随机性,因此C++中产生的随机数也可以称作 pseudo-random numbers(伪随机数)。其实将这些随机数统计起来,会发现这些数字满足了某些相同的性质(当然这些性质不是那么容易看出的,但是一定会有共同点,只是我们单看数据看不出来)。所以,现在我们要研究的是怎么实现随机数产生的方法。

做过贪吃蛇的同学应该有印象(C语言:贪吃蛇),要产生随机数,必须设置随机数种子(seed)。随机数种子相同,产生的随机数也就相同;随机数种子不同,产生的随机数也就不同。因此我们需要想到方法来产生不同的随机数种子。

现在我有两种方法。第一种就是我们在贪吃蛇里用到的方法。那就是调用<time.h>里的clock()函数,将返回的整数作为随机数种子。这个整数是指从程序运行开始计算,到调用这个函数所经过的秒数。但是这里有个问题,一旦我们产生随机数种子的周期小于1s,那么就会产生一系列相同的随机数。总而言之,当产生随机数的周期非常非常小时,用<time.h>已无法满足这一需求。因此,我们采用第二种方法,也就是较为简单的方法,那就是用现有的随机数种子来产生新的种子,也就是Linear-Congruential generator(线性同余数发生器)。这个发生器在下文会详细讲述,用到的公式如下:

// formula
seed = (a*seed) mod m;
// or this one:
seed = (a*seed + c) mod m;
// 其中,a指multiply,c指increment,M指modulus

要产生随机数种子,需要 generators(随机种子发生器) and distributions(分配范围限制)两个”工具”。其实C++中<random>能实现随机数产生。

下面引用cplusplus.com中对<random>的介绍。

———————————————<random>———————————————–
Random
This header introduces random number generation facilities.

This library allows to produce random numbers using combinations of generators and distributions:
Generators: Objects that generate uniformly distributed numbers.
Distributions: Objects that transform sequences of numbers generated by a generator into sequences of numbers that follow a specific random variable distribution, such as uniform, Normal or Binomial.

Distribution objects generate random numbers by means of their operator() member, which takes a generator object as argument:

std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(1,6);
int dice_roll = distribution(generator);  // generates number in the range 1..6 

For repeated uses, both can be bound together:

auto dice = std::bind ( distribution, generator );
int wisdom = dice()+dice()+dice();

上面的代码中有一处需要解释一下,如下:

int dice_roll = distribution(generator);

这一句中的distribution(generator)是使用了运算符重载,重载了()运算符。这在cplusplus.com也给出了解释:

std::uniform_int_distribution::operator()

(1) 
template<class URNG>
result_type operator()(URNG& g);
(2) 
template<class URNG>
result_type operator()(URNG& g, const param_type& parm);

Generate random number
Returns a new random number that follows the distribution’s parameters associated to the object (version 1) or those specified by parm (version 2).

The generator object (g) supplies uniformly-distributed random integers through i

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值