与“模数"运算相比,使用"uniform_int_distribution"有什么优势? [英] What are the advantages of using uniform_int_distribution vs a modulus operation?

查看:222
本文介绍了与“模数"运算相比,使用"uniform_int_distribution"有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据以下结果,使用%运算在两个数字之间生成统一的随机整数几乎比使用std::uniform_int_distribution快3倍:是否有充分的理由使用std::uniform_int_distribution?

According to following results, generating uniform random integers between two numbers using % operation is almost 3 times faster than using std::uniform_int_distribution: Is there any good reason to use std::uniform_int_distribution?

代码:

#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <random>

#include <cstdio>
#include <cstdlib>

using namespace std;

#define N 100000000

int main()
{

clock_t tic,toc;

for(int trials=0; trials<3; trials++)
{
    cout<<"trial: "<<trials<<endl;

    // uniform_int_distribution
    {
        int res = 0;
        mt19937 gen(1);
        uniform_int_distribution<int> dist(0,999);

        tic = clock();
        for(int i=0; i<N; i++)
        {
            int r = dist(gen);
            res += r;
            res %= 1000;
        }
        toc = clock();
        cout << "uniform_int_distribution: "<<(float)(toc-tic)/CLOCKS_PER_SEC << endl;
        cout<<res<<" "<<endl;

    }

    // simple modulus operation
    {
        int res = 0;
        mt19937 gen(1);

        tic = clock();
        for(int i=0; i<N; i++)
        {
            int r = gen()%1000;
            res += r;
            res %= 1000;
        }
        toc = clock();
        cout << "simple modulus operation: "<<(float)(toc-tic)/CLOCKS_PER_SEC << endl;
        cout<<res<<" "<<endl;

    }

    cout<<endl;
}

}

输出:

trial: 0
uniform_int_distribution: 2.90289
538 
simple modulus operation: 1.0232
575 

trial: 1
uniform_int_distribution: 2.86416
538 
simple modulus operation: 1.01866
575 

trial: 2
uniform_int_distribution: 2.94309
538 
simple modulus operation: 1.01809
575 

推荐答案

使用模(%)映射范围时,您将获得统计偏差. rand()到另一个间隔.

You will get statistical bias when you use modulo (%) to map the range of e.g. rand() to another interval.

例如,假设rand()均匀地(无偏差)映射到[0, 32767],而您想通过rand() % 5映射到[0,4].然后,平均会在32768次中产生6554值0、1和2,但是值3和4仅产生6553次(因此3 * 6554 + 2 * 6553 = 32768).

E.g suppose rand() maps uniformly (without bias) to [0, 32767] and you want to map to [0,4] doing rand() % 5. Then the values 0, 1, and 2 will on average be produced 6554 out of 32768 times, but the values 3 and 4 only 6553 times (so that 3 * 6554 + 2 * 6553 = 32768).

偏差很小(0.01%),但取决于您的应用可能会致命.观看Stephan T. Lavavej的演讲" rand()被认为是有害的 "以获取更多详细信息.

The bias is small (0.01%) but depending on your application that could prove fatal. Watch Stephan T. Lavavej's talk "rand() considered harmful" for more details.

这篇关于与“模数"运算相比,使用"uniform_int_distribution"有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆