在C++中设置离散分布

Setting up a Discrete Distribution in C++

本文关键字:分布 设置 C++      更新时间:2023-10-16

经过几个小时的努力,我找不到任何关于我的错误的解释。

我希望计算机选择一个介于0和120(包括120)之间的随机数(加权)。我有一个数组interval[],它包含0到120(包括0和120)之间的数字。我有另一个数组weights[],它保存了选择数组中第I个元素的概率。我想为这些数据定义一个概率分布函数。

这是我试过的。我得到一个错误,说没有构造函数的实例与参数列表匹配。

我的代码片段:

std::vector< int> weights(121);
for (int i = 0; i < 121; i++)
{
    weights[i] = (teamData[i]).S();
}
discrete_distribution<> dist(weights.begin(), weights.end());

从您的链接页面(强调矿)

std::piecewise_constant_distribution产生随机浮点数,它们均匀分布在几个子区间[bi,bi+1,每个子区间都有自己的权重wi区间边界和权重集是分配

它期望浮点权重和边界,并且比边界少一个权重。它也将不是输出0-120之间的整数,而是浮点。

你给它传递了整数权重和边界,所以它无法编译。但即使你修复了它,你仍然会从中获得浮点值…

相反,正如你所发现的,你想要disrete_distribution,你可以这样设置:(根据链接页面文档修改)

#include <iostream>
#include <map>
#include <random>
int main()
{
    // Setup the random bits
    std::random_device rd;
    std::mt19937 gen(rd());
    // Setup the weights (in this case linearly weighted)
    std::vector<int> weights;
    for(int i=0; i<120; ++i) {
        weights.push_back(i);
    }
    // Create the distribution with those weights
    std::discrete_distribution<> d(weights.begin(), weights.end());
    // use the distribution and print the results.
    std::map<int, int> m;
    for(int n=0; n<10000; ++n) {
        ++m[d(gen)/10];
    }
    for(auto p : m) {
        std::cout << p.first*10 << " - "<<p.first*10+9 << " generated " << p.second << " timesn";
    }
}

试试这段代码,看看你是否遇到了同样的问题。

 // piecewise_constant_distribution
#include <iostream>
#include <array>
#include <random>
int main()
{
  const int nrolls = 10000; // number of experiments
  const int nstars = 100;   // maximum number of stars to distribute
  std::default_random_engine generator;
  std::array<double,6> intervals {0.0, 2.0, 4.0, 6.0, 8.0, 10.0};
  std::array<double,5> weights {2.0, 1.0, 2.0, 1.0, 2.0};
  std::piecewise_constant_distribution<double>
    distribution (intervals.begin(),intervals.end(),weights.begin());
  int p[10]={};
  for (int i=0; i<nrolls; ++i) {
    int number = distribution(generator);
    ++p[number];
  }
  std::cout << "a piecewise_constant_distribution:" << std::endl;
  for (int i=0; i<10; ++i) {
    std::cout << i << "-" << i+1 << ": ";
    std::cout << std::string(p[i]*nstars/nrolls,'*') << std::endl;
  }
  return 0;
}