C++ - 随机生成器 伯努利分布(bernoulli distribution) 的 详解 及 代码
2013-12-15 17:42
519 查看
随机生成器 伯努利分布(bernoulli distribution) 的 详解 及 代码
本文地址: http://blog.csdn.net/caroline_wendy/article/details/17335871伯努利分布(bernoulli distribution), 是判断某件事情发生或者未发生的概率;
给定参数p, 可以修改概率的值, 发生概率(true)是p,未发生概率(false)是1-p;
随机库, 提供分布对象bernoulli_distribution, 输出bool值, 发生为true, 未发生为false;
伯努利分布, 概率为0.5时, 可以等概率输出一个二元事件, 如先后顺序;
注意: 引擎和分布对象, 声明在函数外, 则每次调用, 都会产生不同的值, 但却是固定的, 可以使用time(0), 定义不同的引擎;
代码如下:
#include <iostream> #include <vector> #include <string> #include <random> #include <algorithm> #include <cmath> using namespace std; bool play (bool first) { std::default_random_engine e; std::bernoulli_distribution b(0.6); //获胜概率较大 bool win = b(e); if(first) //我们获胜的概率大 return win; else return !win; } int main() { std::string resp; std::default_random_engine e; std::bernoulli_distribution b; do { bool first = b(e); //伯努利生产器 std::cout << (first ? "We go first" : "You get to go first") << std::endl; //判断先后手 std::cout << ((play(first)) ? "congrats, you won" : "sorry, you lost") << std::endl; std::cout << "play again? Enter 'yes' or 'no' " << std::endl; } while (std::cin >>resp && resp[0] == 'y'); return 0; }
输出:
We go first congrats, you won play again? Enter 'yes' or 'no' yes We go first congrats, you won play again? Enter 'yes' or 'no' yes We go first congrats, you won play again? Enter 'yes' or 'no'
本文出自 “永不言弃” 博客,请务必保留此出处http://spikeking.blog.51cto.com/5252771/1387952
相关文章推荐
- C++ - 随机生成器 伯努利分布(bernoulli distribution) 的 详解 及 代码
- 伯努利分布(Bernoulli distribution)
- 详解C++代码反汇编后的堆栈寄存器EBP和ESP
- 3000 fps代码运行步骤详解(C++)
- C++ - 随机访问(random access) 流(stream) 的 详解 及 代码
- C++ - 函数模板(function template) 的 重载(overload) 详解 及 代码
- protobuf 生成的C++代码详解
- 详解C++代码反汇编后的堆栈寄存器EBP和ESP
- C++ boost::asio编程-异步TCP详解及实例代码
- C++ - 指针的引用 详解 及 代码
- TCP三次握手报文 实例详解&&syn flood C/C++ 完整代码实现
- SSL握手通信详解及linux下c/c++ SSL Socket(另附SSL双向认证客户端代码)
- 详解C++中指针(*)、取地址(&)、解引用(*)与引用(&)的区别 (完整代码)
- C++的虚析构详解及实例代码
- C++ - 随机访问(random access) 流(stream) 的 详解 及 代码
- CCF炉石传说题目代码详解C++版(类封装通俗易懂)
- n皇后详解及代码实现/C++
- 数据结构 - 快速排序(Quick Sort) 详解 及 代码(C++)
- 详解C++中指针(*)、取地址(&)、解引用(*)与引用(&)的区别 (完整代码)
- SSL握手通信详解及linux下c/c++ SSL Socket代码举例