您的位置:首页 > 编程语言 > C语言/C++

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: