C ++ 11从频繁变化的范围生成随机数 [英] C++11 Generating random numbers from frequently changing range

查看:117
本文介绍了C ++ 11从频繁变化的范围生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:如何从a未知范围生成(许多)均匀分布的整数?就性能(数百万个生成的数字)而言,首选的方式是什么?

Q: How do I generate (many) uniformly distributed integers from a-priory unknown ranges? What is the prefered way in terms of performance (milions of generated numbers)?

上下文:在我的应用中,我必须在许多地方生成许多伪随机数.我为生成器使用单例模式,以保持应用程序运行的可重复性.在我的情况下,分发始终是统一的,但是问题是,要以C ++ 11样式预先创建分发对象,可能有太多的范围.

Context: In my app I have to generate many pseudo random numbers in many places. I use singleton pattern for the generator to maintain reproducibility of the app's run. Distribution is always uniform in my case, but the problem is that there are far too many possible ranges to pre-made the distribution object in C++11 style.

我尝试过的方法:有两种明显的解决方案,第一是拥有一次性分配对象,第二是使用模将随机数从最大可能范围转换为所需的范围.但是不知何故,我怀疑这些方法最有可能:)

What I tried: There are two obvious solutions to this, first is to have one-time distribution objects and second is to use modulo to transform random number from widest possible range to the desired one. But somehow i doubt these are best possible :)

#include <random>
#include <iostream>
#include "limits.h"
using namespace std;

mt19937 mt;
uniform_int_distribution<int> * fixedDist;
uniform_int_distribution<int> * variableDist;

// this version creates and delete dist after just one use
int getIntFromRange1(int from, int to){
    variableDist = new uniform_int_distribution<int>(from,to);
    int num = (*variableDist)(mt);
    delete variableDist;
    return num;
}

// this version contains modulo
int getIntFromRange2(int from, int to){
    int num = (*fixedDist)(mt);
    int diff = to - from;
    num = num % diff;
    return num + from;
}

int main(){ 
   mt.seed(123456);
   fixedDist= new uniform_int_distribution<int>(0,INT_MAX)

   int a = getIntFromRange1(1,10); // 1 and 10 are just for illustration
   int b = getIntFromRange2(1,10); // can change freely

   cout << "a: " << a << endl; // a: 6
   cout << "b: " << b << endl; // b: 9

   getchar();
}

重复问题

uniform_int_distribution的变化范围

推荐答案

我会做

int getIntFromRange1(int from, int to){
    std::uniform_int_distribution<int> dist(from, to);
    return dist(mt);
}

这篇关于C ++ 11从频繁变化的范围生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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