【问题标题】:using std::uniform_real_distribution in a function that is called in main在 main 调用的函数中使用 std::uniform_real_distribution
【发布时间】:2017-06-13 17:55:53
【问题描述】:

我正在尝试在 main() 中调用的函数中使用 std::uniform_real_distribution。

我在 main() 中按如下方式为生成器播种:

 unsigned seed = 
 std::chrono::system_clock::now().time_since_epoch().count();
 std::default_random_engine generator (seed);
 std::uniform_real_distribution<double> distribution(0.0,1.0);

在我的主要调用中进一步:

double number = distribution(generator)

当我需要一个随机数时。

问题是我还需要(数百万) 函数中的随机数。

想象一个我在 main() 中调用的函数:

int main(){

  void function(){

    number = distribution(generator)
  }

  return 0;
}

如何做到这一点?如何“访问”函数中的随机数生成器。

非常感谢!

【问题讨论】:

  • 你把它传给函数?
  • 不要将时间作为种子,这根本不是随机的。不要使用std::default_random_engine,这通常很糟糕(example)。您可以在我的问题here 中找到正确播种好的 RNG 的方法。

标签: c++ random


【解决方案1】:

你可以用它做一个函数。我建议使用std::mt19937 作为随机数生成器并使用(至少)std::random_device 播种。

类似这样的:

inline
double random_number(double min, double max)
{
    // use thread_local to make this function thread safe
    thread_local static std::mt19937 mt{std::random_device{}()};
    thread_local static std::uniform_real_distribution<double> dist;
    using pick = std::uniform_real_distribution<double>::param_type;

    return dist(mt, pick(min, max));
}

int main()
{
    for(int i = 0; i < 10; ++i)
        std::cout << i << ": " << random_number(2.5, 3.9) << '\n';
}

输出:

1: 3.73887
2: 3.68129
3: 3.41809
4: 2.64881
5: 2.93931
6: 3.15629
7: 2.76597
8: 3.55753
9: 2.90251

【讨论】:

  • 谢谢!阅读您的评论后,我做了类似的事情。 (有效!)
猜你喜欢
  • 2019-04-25
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
相关资源
最近更新 更多