在C++中设置离散分布
Setting up a Discrete Distribution in C++
经过几个小时的努力,我找不到任何关于我的错误的解释。
我希望计算机选择一个介于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;
}
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++/Linux中设置单调时钟的一些技巧
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 嵌套在类中时无法设置成员数据
- 需要帮助设置在C++中使用的Potrace
- 如何在自删除后将对象设置为nullptr
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何在Ubuntu中使用cmake设置qt4
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 如何在boost beast http请求中设置http头
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 如何在24位SDL_Surface上设置像素的颜色
- std::设置自定义比较器
- 如何设置一个范围来提取我想要获得的信息
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- 在运行时为随机分布类成员设置最小和最大边界?
- 如何在C++中设置均匀分布的参数?
- 在C++中设置离散分布