相关疑难解决方法(0)

如何使用<random>在多种类型的编译器和内核上生成相同的随机数序列?

问题

我需要在不同的机器和编译器上生成相同的(伪)随机数序列.如果我使用相同的内核,似乎g ++中的mersenne twister(MT)的实现效果很好:无论我是在新机器上编译我的程序,使用g ++ 4.9或4.7,我都得到相同的随机数.但是如果我使用较旧的内核或者我改用Visual Studio的编译器,我会得到不同的.没关系,因为没有保证可以mersenne_twister_engine::seed将内部状态设置为不同的编译器.

我已经尝试过的

我认为应用于operator<<发生器会产生一个独特的结果,可以用来设置其他机器上的发生器operator>>,但是如果mt19937它似乎不起作用.为了说清楚,在计算机上AI有代码

mt19937 generator1A;
uniform_int_distribution<int> distribution(0, 1000);

cout << "Generating random numbers with seed 1000" << endl;

generator1A.seed(1000);
generator1A(); //to advance the state by one so operator>> will give a longer output; this is not necessary indeed
ofstream test("testseed1000.txt");
test << generator1A << endl;

for (int i = 0; i < 10; ++i)
    cout << distribution(generator1A) << endl;
Run Code Online (Sandbox Code Playgroud)

它产生252,590,893,......和一个长文件.我将文件传输到另一台机器B,并运行以下代码:

mt19937 generator1B, generator2B;
uniform_int_distribution<int> distribution(0, 1000); …
Run Code Online (Sandbox Code Playgroud)

c++ random c++11

18
推荐指数
2
解决办法
1778
查看次数

实现之间的随机输出不同

我用libstdc ++,libc ++和dinkumware尝试过这个程序:

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

int main()
{
    std::vector<int> v(10);

    std::mt19937 rand{0};
    std::uniform_int_distribution<> dist(
        1, 10
    );

    std::generate_n(v.begin(), v.size(),
        std::bind(dist, rand));

    for (auto i : v)
        std::cout << i << " ";
}
Run Code Online (Sandbox Code Playgroud)

输出分别是:

6 6 8 9 7 9 6 9 5 7 

6 1 4 4 8 10 4 6 3 5 

5 10 4 1 4 10 8 4 8 4 
Run Code Online (Sandbox Code Playgroud)

每次运行的输出都是一致的,但正如您所看到的,它们是不同的.说明?

c++ random c++11

5
推荐指数
1
解决办法
217
查看次数

随机数生成器性能因平台而异

我正在 C++ 中测试随机数生成器的性能,并得到了一些我不明白的非常奇怪的结果。

我已经测试了 std::rand 与使用 std::minstd_rand 的 std::uniform_real_distribution 。

计时 std::rand 代码

auto start = std::chrono::high_resolution_clock::now();

for (int i = 0; i < 1000000; ++i)
    std::rand();

auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
std::cout << "Elapsed time: " << elapsed.count() * 1000 << " ms\n";
Run Code Online (Sandbox Code Playgroud)

使用 std:minstd_rand 计时 std::uniform_real_distribution 的代码

std::minstd_rand Mt(std::chrono::system_clock::now().time_since_epoch().count());
std::uniform_real_distribution<float> Distribution(0, 1);

auto start = std::chrono::high_resolution_clock::now();

for (int i = 0; i < 1000000; ++i)
    Distribution(Mt);

auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = …
Run Code Online (Sandbox Code Playgroud)

c++ random performance c++17

2
推荐指数
1
解决办法
282
查看次数

标签 统计

c++ ×3

random ×3

c++11 ×2

c++17 ×1

performance ×1