生成随机骰子卷并测量结果的频率

时间:2015-03-02 04:41:02

标签: c++ boost random

这里我正在掷骰子并将结果存储在地图中(int表示数字的出现,很长的频率,即出现/试验)。这是典型的输出:

Please select the number of trials:
100
Dice roll of 1 has 327% outcomes
Dice roll of 2 has 16722170% outcomes
Dice roll of 3 has 327% outcomes
Dice roll of 4 has 14872209% outcomes
Dice roll of 5 has 327% outcomes
Dice roll of 6 has 16724069% outcomes

正如您所看到的那样,频率都是混乱的。它们应该总计为1.我已经尝试弄乱了精度,但这似乎并不是我问题的根源。代码很简单。任何人都可以查明我的问题吗?亲切的问候。

#include <boost/random.hpp> 
#include <iostream>
#include <ctime>            
#include <boost/Random/detail/const_mod.hpp> // LCG class
#include <map>

using namespace std;


int main()
{
    //throwind dice
    //Mersenne Twister
    boost::random::mt19937 myRng;

    //set the seed
    myRng.seed(static_cast<boost::uint32_t> (time(0)));

    //uniform in range [1,6]
    boost::random::uniform_int_distribution<int> six(1,6);

    map<int, long> statistics;    //structure to hold outcome + frequencies
    int outcome;    //current outcome

    cout << "Please select the number of trials:" << endl;
    int trials;    //# of trials
    cin >> trials;
    int oc1; int oc2; int oc3; int oc4; int oc5; int oc6;    //outcomes
    for (int i = 0; i < trials; ++i)
    {
        outcome = six(myRng);

        if (outcome == 1)
        {
            oc1++;
            statistics[1] = oc1 / trials;
        }

        if (outcome == 2)
        {
            oc2++;
            statistics[2] = oc2 / trials;
        }

        if (outcome == 3)
        {
            oc3++;
            statistics[3] = oc3 / trials;
        }

        if (outcome == 4)
        {
            oc4++;
            statistics[4] = oc4 / trials;
        }

        if (outcome == 5)
        {
            oc5++;
            statistics[5] = oc5 / trials;
        }

        if (outcome == 6)
        {
            oc6++;
            statistics[6] = oc6 / trials;
        }
    }

    for (int j = 1; j <= 6; ++j)
        cout << "Dice roll of " << j << " has " << statistics[j] << "% outcomes" << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:1)

很简单,你没有初始化oc1, oc2,等等。

但是你的代码可以使用一些简化:

int oc[6] = {};
for (int i = 0; i < trials; ++i)
{
    outcome = six(myRng);
    oc[outcome-1]++;
    statistics[outcome] = oc[outcome-1] / trials;
}

这不仅会初始化值,还会缩短循环次数。

但是,正如评论建议的那样,如果你想要浮点数,你需要改变你的类型以允许浮点值,而不是整数。