关于使用 C++ 的概率模型的问题

Question About a Probability Model Using C++

我试图从理论上解决概率问题,然后在 C++ 上对其建模,但我的代码输出的概率与理论概率不同。

问题:

一枚平衡的硬币被抛了三次。计算三次抛掷中恰好有两次正面朝上的概率。

答案:

样本space:{(H,H,H), (H,H,T), (H,T,H), (H,T,T), (T,T, T), (T,T,H), (T,H,T), (T,H,H)}

三次抛掷中恰好有两次正面朝上的概率 = 3/8

C++代码:

#include <iostream>
#include <time.h>
#include <stdlib.h>

bool TossCoinXNumber(int x);
int TossCoin();
void CalcProbability(int x);

using namespace std;

int main()
{
    srand (time(NULL));
    CalcProbability(1000000);
    return 0;
}

int TossCoin(){
    int toss = rand() % 2;
    return toss;
}

bool TossCoinXNumber(int x){
    int heads=0;
    int tails = 0;
    for(int i = 0; i < x; i++){
        if(TossCoin() == 1){
            heads++;
        }
        else if(TossCoin() == 0){
            tails++;
        }

    }
            if(heads == 2 && tails == 1){
            return true;
        }
    return false;
}

void CalcProbability(int x){
    double probability = 0.0;
    double count = 0.0;
    for(int i = 0; i < x; i++){
        if(TossCoinXNumber(3) == true){
            count++;
        }
    }
    probability = (count*1.0) / (x*1.0);
    cout << probability;
}

代码输出:0.187053

这与理论概率3/8不同

正如 n. 1.8e9-where's-my-share m. 正确指出的那样,您正在调用 TossCoin() 两次。这是解决问题的修改代码:

#include <stdlib.h>
#include <time.h>

#include <iostream>

bool TossCoinXNumber(int x);
int TossCoin();
void CalcProbability(int x);

using namespace std;

int main()
{
    srand(time(NULL));
    CalcProbability(1000000);
    return 0;
}

int TossCoin()
{
    int toss = rand() % 2;
    return toss;
}

bool TossCoinXNumber(int x)
{
    int heads = 0;
    int tails = 0;
    for (int i = 0; i < x; i++)
    {
        int toss = TossCoin();
        if (toss == 1)
        {
            heads++;
        }
        else if (toss == 0)
        {
            tails++;
        }
    }
    if (heads == 2 && tails == 1)
    {
        return true;
    }
    return false;
}

void CalcProbability(int x)
{
    double probability = 0.0;
    double count = 0.0;
    for (int i = 0; i < x; i++)
    {
        if (TossCoinXNumber(3) == true)
        {
            count++;
        }
    }
    probability = (count * 1.0) / (x * 1.0);
    cout << probability;
}

这是我更喜欢的较短的代码:

#include <iostream>
#include <random>

 using namespace std;

 int main(void)
{
     int tries = 1000000, count = 0;

    for (int i = 0; i < tries; ++i)
    {
        int heads = 0;
        for (int j = 0; j < 3; ++j) heads += (rand() % 2);
        count += (heads == 2);
    }

    cout << count / float(tries) << endl;
}

在此代码中,比较的整数结果用于递增 heads, count,因此我们没有任何 if