我找不到关于Boost_discrete_distribution的大量文档。在Google大量搜索之后,我什至找不到该类具有的方法列表,以及它们是否有功能来重新分配概率。
就我而言,我正在编写一种进化动力学算法。在每个时间步骤中,可以随机选择种群成员以死亡或繁殖。因此,离散分布中的条目总数几乎每次迭代都会更改。
我想在仿真开始之前定义一个对象,称为gillespie_dist
(控制此Gillespie算法的离散分布)。但是我希望在每次迭代结束时潜在地更改特定值和/或向gillespie_dist
添加新值,特别是不想在每次迭代时都创建离散离散的新实例。
有什么好的方法。是否有将新值推送到discrete_distribution
对象的方法,是否有更改特定索引处的分布值的方法,或者更好的方法是使用here中提到的 vector 迭代器思想以某种方式“重新初始化”整个分布?
最佳答案
我研究了std::discrete_distribution的gcc libstdc++ 4.7实现的代码。
权重作为vector<double>
存储在私有(private)成员中。在公共(public)接口(interface)中无法访问其调整大小方法。
我将尝试找出其operator()的实现(看起来像在cpp中),滚动自己的应该没有问题。
这是主要 Action ,下面是我的解释:
template<typename _IntType>
void
discrete_distribution<_IntType>::param_type::
_M_initialize()
{
if (_M_prob.size() < 2)
{
_M_prob.clear();
return;
}
const double __sum = std::accumulate(_M_prob.begin(),
_M_prob.end(), 0.0);
// Now normalize the probabilites.
__detail::__transform(_M_prob.begin(), _M_prob.end(), _M_prob.begin(),
std::bind2nd(std::divides<double>(), __sum));
// Accumulate partial sums.
_M_cp.reserve(_M_prob.size());
std::partial_sum(_M_prob.begin(), _M_prob.end(),
std::back_inserter(_M_cp));
// Make sure the last cumulative probability is one.
_M_cp[_M_cp.size() - 1] = 1.0;
}
template<typename _IntType>
template<typename _UniformRandomNumberGenerator>
typename discrete_distribution<_IntType>::result_type
discrete_distribution<_IntType>::
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __param)
{
if (__param._M_cp.empty())
return result_type(0);
__detail::_Adaptor<_UniformRandomNumberGenerator, double>
__aurng(__urng);
const double __p = __aurng();
auto __pos = std::lower_bound(__param._M_cp.begin(),
__param._M_cp.end(), __p);
return __pos - __param._M_cp.begin();
}
因此,基本上,它在初始化时计算辅助 vector
_M_cp
,它实质上是权重的离散累积密度函数。因此,生成样本仅意味着生成一个统一的随机变量,并在累积分布中搜索该变量的首次出现(这是上面的lower_bound 调用),并返回其索引。例如,如果权重 vector 为:
{ 1, 2, 1, 3 }
那么cp的计算公式为:
{ 1, 1+2, 1+2+1, 1+2+1+3 }
=
{ 1, 3, 4, 7 }
所以我统一选择0..6并得到4,所以我选择了第三个。
关于c++ - boost::random::discrete_distribution是否可以动态调整大小?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9952106/