gpt4 book ai didi

c++ - RNG 函数 C++

转载 作者:行者123 更新时间:2023-11-30 03:16:18 24 4
gpt4 key购买 nike

我正在尝试用 C++ 编写一个函数,每次返回一个介于 0 和 1 之间的随机 float / double ,每次都具有不同的值。

我尝试了 srand、rand 和 RAND_MAX 的几种不同方向,但每次运行代码时,每次都应更改的某些值具有常量值。我有一个术语 x = 20 * randomnumber() 但每次它都会为 x 返回相同的值。无论我多久运行一次代码。这是我的功能。

double randomnumber()
{
srand(time(NULL))
double r1 = ((double)rand()) / RAND_MAX);

return r1;
}

我想要它做的是生成一个介于 0 和 1 之间的 float ,这样当我乘以另一个整数时,我得到一个介于 0 和该整数之间的值。注意:我知道有一个函数,我可以在 0 和数字之间明确地执行此操作,但我正在编写的代码最好每次都乘以一个随机数。

提前致谢。

最佳答案

最好的方法是使用 C++ 的随机数库,不是 rand()

我们可以很容易地做到这一点:

#include <random>

double randomnumber() {
// Making rng static ensures that it stays the same
// Between different invocations of the function
static std::default_random_engine rng;

std::uniform_real_distribution<double> dist(0.0, 1.0);
return dist(rng);
}

每次都会生成一个新的随机数,并且每次运行程序时都会生成相同的随机数序列。如果我跑

int main() {
for(int i = 0; i < 10; i++) {
std::cout << randomnumber() << '\n';
}
}

那我看看

0.131538
0.45865
0.218959
0.678865
0.934693
0.519416
0.0345721
0.5297
0.00769819
0.0668422

随机初始化生成器。如果您想在每次运行程序时生成不同的随机数,则必须使用随机种子初始化生成器。生成一个非常容易:

auto getRandomSeed() 
-> std::seed_seq
{
// This gets a source of actual, honest-to-god randomness
std::random_device source;

// Here, we fill an array of random data from the source
unsigned int random_data[10];
for(auto& elem : random_data) {
elem = source();
}

// this creates the random seed sequence out of the random data
return std::seed_seq(random_data + 0, random_data + 10);
}

一旦我们有了这个种子,我们就可以修改 randomnumber() 来创建带有随机种子的生成器:

#include <random>

double randomnumber() {
// Making rng static ensures that it stays the same
// Between different invocations of the function
static auto seed = getRandomSeed();
static std::default_random_engine rng(seed);

std::uniform_real_distribution<double> dist(0.0, 1.0);
return dist(rng);
}

关于c++ - RNG 函数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56435506/

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