以给定概率得出 true 或 false

2024-01-07

我正在尝试用 C++ 编写一个函数,该函数将根据给定的概率返回 true 或 false。因此,例如,如果给定的概率为 0.634,则该函数有 63.4% 的机会返回 true。我尝试了几种不同的方法,但都失败了。有什么帮助吗?


如果您想在 C++11 中执行此操作,您可以使用其各种随机数引擎,并结合uniform_real_distribution提供良好的结果。下面的代码演示了:

#include <random>

std::knuth_b rand_engine;  // replace knuth_b with one of the engines listed below
std::uniform_real_distribution<> uniform_zero_to_one(0.0, 1.0);

bool random_bool_with_prob( double prob )  // probability between 0.0 and 1.0
{
    return uniform_zero_to_one(rand_engine) >= prob;
}

或者,您可以使用bernoulli_distribution,这直接给你一个bool以指定的概率。它所花费的概率就是返回 true 的概率,因此它正是您所需要的:

#include <random>

std::knuth_b rand_engine;  // replace knuth_b with one of the engines listed below

bool random_bool_with_prob( double prob )  // probability between 0.0 and 1.0
{
    std::bernoulli_distribution d(prob);
    return d(rand_engine);
}

如果你的概率是固定的,那么你可以将它移出函数,如下所示:

#include <random>

std::knuth_b rand_engine;  // replace knuth_b with one of the engines listed below
std::bernoulli_distribution random_bool_generator( prob );  // replace "prob" with your probability

bool random_bool()
{
    return random_bool_generator( rand_engine );
}

或者如果你想变得更漂亮,你可以将它们绑定在一起:

#include <random>
#include <functional>

std::knuth_b rand_engine;  // replace knuth_b with one of the engines listed below
std::bernoulli_distribution random_bool_generator( prob );  // replace "prob" with your probability

auto random_bool = std::bind( random_bool_generator, rand_engine )

// Now call random_bool() to get your random boolean with the specified probability.

您可以更换knuth_b与任何标准引擎:

  • std::linear_congruential_engine
  • std::mersenne_twister_engine
  • std::subtract_with_carry_engine

或更多,它们是上述版本,以各种方式参数化。我的参考列出了以下内容:

  • std::default_random_engine(实现定义。)
  • std::minstd_rand0
  • std::minstd_rand
  • std::mt19937
  • std::mt19337_64
  • std::ranlux24_base
  • std::ranlux48_base
  • std::ranlux24
  • std::ranlux48
  • std::knuth_b

如果这还不够,还有一些标准适配器可以进一步扰乱随机数序列:

  • std::discard_block_engine它通过每次丢弃给定数量的生成值来调整引擎。
  • std::independent_bits_engine它使引擎产生具有指定位数的随机值。 (对您的特殊需求来说并不重要。)
  • std::shuffle_order_engine它通过排列生成值的顺序来适应引擎。

第二个列表中的生成器源自第一个列表中的基本生成器,具有特定参数、适配器或两者兼而有之。例如,knuth_b相当于shuffle_order_engine< linear_congruential_engine< uint32_t, 16807, 0, 2147483647>, 256>,根据我的参考书。 (C++ 标准库,第二版,作者 Nicolai Josuttis,一本很棒的参考书。)

您可以在线找到更多信息,包括此处的简要介绍:http://en.wikipedia.org/wiki/C++11#Extensible_random_number_facility http://en.wikipedia.org/wiki/C++11#Extensible_random_number_facility

这里有更多文档:http://en.cppreference.com/w/cpp/numeric/random http://en.cppreference.com/w/cpp/numeric/random

您可能想要修改以下声明rand_engine以上提供种子。上面的示例使用默认种子。如果您想要不同的种子,请参阅 cppreference.com 了解如何为其播种。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以给定概率得出 true 或 false 的相关文章

随机推荐