在 main 中调用的函数中使用 std::uniform_real_distribution [英] using std::uniform_real_distribution in a function that is called in main

查看:105
本文介绍了在 main 中调用的函数中使用 std::uniform_real_distribution的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use the std::uniform_real_distribution in a function that is called in main().

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

I seed the generator as follows in 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);

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

further on in main i call:

double number = distribution(generator)

当我需要一个随机数时.

when i need a random number.

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

The problem is that i also need ( many millions ) of random numbers in a function.

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

imagine a function that i call in main():

int main(){

  void function(){

    number = distribution(generator)
  }

  return 0;
}

如何做到这一点?如何在函数中访问"随机数生成器.

how to do this? how to "access" the random number generator in a function.

非常感谢!

推荐答案

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

You can make a function out of it. I recommend using std::mt19937 as the random number generator and seeding it with (at least) 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

这篇关于在 main 中调用的函数中使用 std::uniform_real_distribution的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆