【问题标题】:Execute code x percent of the time执行代码 x% 的时间
【发布时间】:2016-04-16 18:10:31
【问题描述】:

我有一只动物在一个while循环中生活了很多天。

一天结束时,她有 40% 的机会生孩子,

class Animal
{
public:
  double chance_of_birth;
  ...

  public Animal(..., int chance)
  {
    this.chance_of_birth = chance;
    ...
  }
}

// create this animal
Animal this_animal = new Animal(..., .50);

鉴于我创造的每只动物都有特定的生育机会, 我怎样才能写出一个只在chance_of_birth% 的时间内评估为真的条件?

我知道我想用rand(),但我以前从来没有这样用过。

沿线

if(this_animal->chance_of_birth ???)
{
  //will give birth
}

【问题讨论】:

  • 如果你想使用 rand(),它会返回一个 int,你必须这样做:double rn = rand() % 10000; rn /= 10000.0; if (chance > rn) {/*code*/}
  • @DarthRubik 这对我很有帮助,谢谢!
  • 这会有一点偏差,因为 rand 从 2³¹ 的可能性中返回(据称)均匀分布的值。

标签: c++ random


【解决方案1】:

由于c++11,您可以使用库<random>
在下面的示例中,我使用std::uniform_real_distribution<> 来生成 0 - 1 范围内的随机浮点值

#include <iostream>
#include <random>
using namespace std;

double random(int min, int max)
{ // we make the generator and distribution 'static' to keep their state
  // across calls to the function.
    std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_real_distribution<> dis(min, max);
    return dis(gen);
}

int main()
{
    double f = random(0,1); // range 0 - 1
    cout << f << '\n';
}

现在您可以在 if statement 中使用该随机浮点值,仅在条件为真时运行。

if (f <= 0.40) { ... }

【讨论】:

  • 有一个小疏忽:std::mt19937 PRNG 应该是 static(或 thread_local),而不是 random 函数。目前random 每次都不会返回相同的值,因为每次调用时 PRNG 都会使用不同的种子进行初始化。然而,它不是最理想的,因为它很慢并且不能保证gen 的顺利运行。
  • 如果gen 不是static 每次调用random 意味着: 1. 调用rd()random_device 的许多实现的性能一旦熵池急剧下降已用尽) 2. 构造一个新的(不是那么小)mt19937 对象。此外,通常您只播种一次 PRNG(例如 stackoverflow.com/a/7320944/3235496
猜你喜欢
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-28
相关资源
最近更新 更多