【问题标题】:Generating random dice rolls and measuring frequency of outcomes生成随机掷骰子并测量结果的频率
【发布时间】:2015-03-02 12:58:25
【问题描述】:

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

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;
}

【问题讨论】:

  • 您是否正在初始化结果变量? (oc1oc6
  • 我试过“int 结果 = 六(myRng);”但没有成功。我还将 oc1、oc2、oc3 等初始化为 0,但这给了我直接的“0% 结果”。
  • J-Kubik 发现了您的问题。 int 的默认初始化是一个随机数(通常是内存中已经存在的任何东西)。只需将所有 oc 变量设置为 0 就可以了
  • 还有一个额外的问题——你的百分比不能用 int 计算——你的除法操作系统丢弃了结果。例如使用(oc1 * 100)/trials
  • 您的 ocN 变量未初始化为任何值。除非您将它们初始化为 0,否则它们不太可能从 0 开始。 oc1 / trials 也是整数除法,小数结果为 0。

标签: c++ boost random


【解决方案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;
}

这不仅初始化了值,而且缩短了循环。

但是,正如评论所建议的,如果您想要浮点,则需要更改类型以允许浮点值,而不是整数。

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 2013-02-15
    • 1970-01-01
    • 2013-06-12
    • 2014-02-28
    • 2014-10-07
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    相关资源
    最近更新 更多