在编译时在C ++中生成随机数 [英] Generate random numbers in C++ at compile time

查看:155
本文介绍了在编译时在C ++中生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在编译时使用C ++ 11的 random 库预先计算随机值。我主要是下面的例子。我在这里做错了什么?

I'm trying to precompute random values using C++11's random library at compile time. I'm mostly following examples. What am I doing wrong here?

using namespace std;
#include <iostream>
#include <vector>
#include <random>

vector<double> rands;
typedef std::mt19937_64 RNG;
uint64_t seed_val;
RNG rng; 

void initialize() {
     rng.seed(seed_val);
}

constexpr vector<double> generate_random( )                 //size_t numbers)
{   
    int numbers = 1000;
    std::uniform_real_distribution<double> zero_one(0.0, 1.0);
        for (unsigned int i = 0; i < numbers; i++) { 
             double rand_num = zero_one(rng);
             rands.push_back( rand_num );
    }
    return rands;
}

int main()
{
    cout << "TMP rands";
    for_each( rands.begin(), rands.end(), [] (double value)
    {
        cout<<value<<endl;
    });
}

这里是一个编译时随机数生成器的例子,从这里,但认为这可能对任何人谁看起来这样: / p>

Here's an example compile-time random number generator shamelessly stolen from here, but thought it might be useful for anyone who looks this up:

template<u32 S, u32 A = 16807UL, u32 C = 0UL, u32 M = (1UL<<31)-1>
struct LinearGenerator {
    static const u32 state = ((u64)S * A + C) % M;
    static const u32 value = state;
    typedef LinearGenerator<state> next;
    struct Split { // Leapfrog
        typedef LinearGenerator< state, A*A, 0, M> Gen1;
        typedef LinearGenerator<next::state, A*A, 0, M> Gen2;
    };
};


推荐答案

只有 constexpr 函数和常量表达式可以在编译时评估。这会排除< chrono> < random>

Only constexpr functions and constant expressions may be evaluated at compile time. That rules out <chrono> and <random>.

你可以访问 __ TIME __ 预处理器宏,并定义由单行 constexpr 函数。

What you can do is access the __TIME__ preprocessor macro and define your own PRNG composed of one-line, constexpr functions.

这篇关于在编译时在C ++中生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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