c++ - 为什么从函数调用时 c++11 std::normal_distribution 返回相同的模式?

标签 c++ c++11 random normal-distribution

我想向信号引入高斯噪声。我研究了如何使用 C++11 std::normal_distribution 的几个示例,并且使用此示例能够实现预期的随机结果:https://stackoverflow.com/a/32890945/3424478

#include <functional>
#include <iostream>
#include <iterator>
#include <random>

int main() {
    // Example data
    std::vector<double> data = {1., 2., 3., 4., 5., 6.};

    // Define random generator with Gaussian distribution
    const double mean = 0.0;
    const double stddev = 0.1;
    auto dist = std::bind(std::normal_distribution<double>{mean, stddev},
                          std::mt19937(std::random_device{}()));

    // Add Gaussian noise
    for (auto& x : data) {
        x = x + dist();
    }

    // Output the result, for demonstration purposes
    std::copy(begin(data), end(data), std::ostream_iterator<double>(std::cout, " "));
    std::cout << "\n";

    return 0;
}

当我从 main() 多次调用 dist() 时,它可以完美地工作,并且对于不同的 vector 也可以正常工作,但是一旦我将代码移动到函数中它总是返回相同的恒定噪声模式,我想调用此函数来修改引用信号并将其分配给不同的数组或 vector 。这是我的代码:

void AddGaussianNoiseToPixel(std::array<short int, N_SLICES>& pixel_array, const std::array<short int, N_SLICES>& reference_pixel)
{
    const float mean   = 0.0;
    const float stddev = 2.0;
    auto dist = std::bind(std::normal_distribution<float>{mean, stddev},
                          std::mt19937(std::random_device{}()));

    for (const auto& slice : reference_pixel) 
    {
        pixel_array[&slice-&reference_pixel[0]] = rint(slice+dist());
    }
}

我读过类似的帖子:https://stackoverflow.com/a/22921927/3424478发生这种情况的原因是种子传递给随机生成器,但事实并非如此,因为我将 std::random_device{}() 传递给随机引擎std::mt19937()

编辑:

我在 Windows 7 中使用 MinGW-W64-builds-4.3.5

最佳答案

这很可能与 feature/bug in mingw 有关这使得 std::random_device 具有确定性。您可以通过添加另一个熵源来规避此问题,例如当前时间:

  uint64_t seed = std::random_device{}() |
    std::chrono::system_clock::now().time_since_epoch().count();

但是,更好的解决方案是仅使用一个引擎和分发对象。一个简单的方法是在新函数中使用静态变量。

关于c++ - 为什么从函数调用时 c++11 std::normal_distribution 返回相同的模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52418053/

相关文章:

c++ - push_back 与 pair<float,int> 交互的困惑

c++ - 未调用 move 构造函数

javascript - 选择随机数组,然后选择该数组中的一个元素

java - 返回随机字符串数组

c++ - 迭代器访问冲突的原因及解决方案

c++ - OpenCV 中的 vc10、vc11 和 vc12 库有什么区别?

android - 是否可以从Oboe的同一麦克风打开2个流?

c - gcc 编译 c++ 时不带任何标志

C++11 - 将非静态数据成员声明为 'auto'

c - 在动态数组C中生成不重复的随机数