简体   繁体   English

如何使C ++中的类的成员函数每次调用时生成不同的随机数?

[英]How to make a member function of a class in C++ generate a different random number each time it is called?

I have a class which also includes a random number engine and its distribution: 我有一堂课,其中还包括一个随机数引擎及其分布:

#include <iostream>
#include <cmath>
#include <random>
#include <chrono>

class C
{ 
  public:
      typedef std::mt19937_64 engine;
      typedef std::uniform_real_distribution<double> distribution;
      .
      .
      .

  protected:
      engine rng;
      distribution dist;
      void func();
      .
      .
      .
};

Since the constructor is called only once, I put the seed in it: 由于构造函数仅被调用一次,因此将种子放入其中:

C::C()
{   .
    .
    .  
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    distribution dist(0.0, pow(10,12));
    engine rng(seed);
}

The following member function is supposed to generate a random number and is going to be called lots of times in a single run of the program: 以下成员函数应该生成一个随机数,并且在程序的一次运行中将被多次调用:

void C::func()
{    .
     .
     .
     double randNum = floor(dist(rng));
     std::cout << randNum << std::endl;      
     .
     .
     .
}

However, each time it generates the number 0 as the random number. 但是,每次生成数字0作为随机数。 It seems that dist(rng) is not doing its job. 似乎dist(rng)并未完成其工作。

I really need to find the problem and correct the output. 我真的需要找到问题并更正输出。 I would appreciate any help. 我将不胜感激任何帮助。

You define your dist and eng variables in the class 您可以在类中定义disteng变量

protected:
  engine rng;
  distribution dist; // Here
  void func();

And in the constructor you define another with the same name 然后在构造函数中定义另一个同名

C::C()
{   .
    .
    .  
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    distribution dist(0.0, pow(10,12)); // Here
    engine rng(seed);
}

I assume you want the latter to be an assignment, not a new variable. 我假设您希望后者是一个赋值,而不是一个新变量。 Then you will get the numbers you want. 然后,您将获得所需的号码。

C::C()
{   .
    .
    .  
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    dist = distribution(0.0, pow(10,12)); // Here
    rng = engine(seed);
}

Or with initialization 或初始化

C() : dist(0.0, pow(10, 12)),
  rng(std::chrono::system_clock::now().time_since_epoch().count())

Sami is close, but you should really be initialising these members: 萨米(Sami)接近,但您应该真正初始化这些成员:

C::C()
  : dist(0.0, pow(10, 12))
  , rng(std::chrono::system_clock::now().time_since_epoch().count())
{}

In the constructor, you're creating a local variable dist that hides the class member, while the class member gets default-initialized. 在构造函数中,您要创建一个局部变量dist ,该变量将隐藏类成员,而该类成员将被默认初始化。 A default-initialized uniform_real_distribution generates values in the range [0,1), which floor will always turn into 0. 默认初始化的uniform_real_distribution生成[0,1)范围内的值,该floor将始终变为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM