题目
函数f0,黑盒,功能是以不定概率p得到返回0和1。编写函数,功能是等概率生成0和1 。
分析
设生成0的概率为p,则生成两次,有四种情况,00、01、10、11。概率分别为pp、p(1-p)、(1-p)p、()1-p)(1-p),取得01与10,等概率。其余两种则返回重新生成。
代码
f0为随机生成p概率生成0和1。
int f0()
{
double p = 0.654;
return static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / 1)) < p ? 0 : 1;
} //f0以固定概率p,返回0和1,不知具体内容。
f1为等概率返回0、1。
int f1()
{
int ans = 0;
do
{
ans = f0();
} while (ans==f0());
return ans;
}//利用f0,改写成等概率返回0和1
main函数中为测试内容
完整代码
//P15 不等概率随机到等概率随机
#include <iostream>
using namespace std;
int f0()
{
double p = 0.654;
return static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / 1)) < p ? 0 : 1;
} //f0以固定概率p,返回0和1,不知具体内容。
int f1()
{
int ans = 0;
do
{
ans = f0();
} while (ans==f0());
return ans;
}//利用f0,改写成等概率返回0和1
int main()
{
srand(static_cast <unsigned> (time(0)));
int counts_0 = 0, counts_1 = 0;
for (int i = 0; i < 100000; i++)
{
if (f1() == 0)
counts_0 += 1;
if (f1() == 1)
counts_1 += 1;
}
cout << counts_0 << endl;
cout << counts_1 << endl;
return 0;
}