gpt4 book ai didi

c++ - 在编译时在 C++ 中生成随机数

转载 作者:IT老高 更新时间:2023-10-28 23:27:48 25 4
gpt4 key购买 nike

我正在尝试在编译时使用 C++11 的 random 库预先计算随机值。我主要遵循示例。我在这里做错了什么?

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;
});
}

这是一个编译时随机数生成器的示例,该示例无耻地从 here 窃取。 ,但认为它可能对查找此内容的任何人有用:

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> .

您可以访问 __TIME__预处理宏并定义你自己的由一行组成的PRNG,constexpr功能。

关于c++ - 在编译时在 C++ 中生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11498304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com