在C ++中设置离散发行版 [英] Setting up a Discrete Distribution in C++

查看:62
本文介绍了在C ++中设置离散发行版的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过数小时的努力,我找不到我的错误的任何解释.

After hours of struggling with this issue, I cannot find any explanations for my error.

我希望计算机选择0到120(含)之间的随机数(加权数).我有一个数组interval [],其中保存着0到120(含)之间的数字.我还有另一个数组weights [],其中包含在数组中选择第ith个元素的概率.我想为这些数据定义一个概率分布函数.

I want the computer to pick a random number (weighted) between 0 and 120 (inclusive). I have an array, interval[], which holds the numbers from 0 to 120 (inclusive). I have another array, weights[], which holds the probabilities for choosing the ith element in the array. I want to define a probability distribution function for these data.

这是我尝试过的.我收到一条错误消息,指出没有构造函数实例与参数列表匹配.

Here is what I tried. I get an error saying that no instance of constructor matches the argument list.

我的代码段

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 产生随机的浮点数数字,它们均匀分布在几个数字中子间隔 [b i ,b i + 1 ),每个子间隔都有自己的权重 w i .一套区间边界和权重集是此参数分布.

std::piecewise_constant_distribution produces random floating-point numbers, which are uniformly distributed within each of the several subintervals [bi, bi+1), each with its own weight wi. The set of interval boundaries and the set of weights are the parameters of this distribution.

它期望浮点权重和边界,并且权重比边界小一.它还会输出0-120之间的整数,但会浮动.

It expects floating point weights and boundaries, and one less weight than boundaries. It will also not output integers between 0-120, but floats.

您正在为其传递整数权重和边界,因此它无法编译.但是,即使您修复了该问题,仍然会从中获得浮点值...

You're passing it integer weights and boundaries so it fails to compile. But even when you fix that you're still going to get floating point values out of it...

相反,您发现要使用 disrete_distribution ,您可以这样设置:(从链接页面的文档中修改)

Instead as you've discovered you want the disrete_distribution which you can set up like this: (modified from the linked pages documentation)

#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 << " times\n";
    }
}

这篇关于在C ++中设置离散发行版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆