我应该调用reset()在我的C ++ std随机分布,以清除隐藏状态? [英] Should I call reset() on my C++ std random distribution to clear hidden state?

查看:165
本文介绍了我应该调用reset()在我的C ++ std随机分布,以清除隐藏状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将来自C ++ 11标准库的随机数分布包含在简单函数中,该函数将分布的参数和生成器实例作为参数。例如:

I would like to wrap the random number distributions from the C++11 standard library with simple functions that take as arguments the distribution's parameters and a generator instance. For example:

double normal(double mean, double sd, std::mt19937_64& generator)
{
    static std::normal_distribution<double> dist;
    return dist(generator, std::normal_distribution<double>::param_type(mean, sd));
}

我想避免在分布对象中的任何隐藏状态,这个包装函数只取决于给定的参数。 (可能的,每个调用这个函数可以采用不同的生成器实例。)理想情况下,我会使分布实例 static const 然而,分布的 operator()不是一个const函数,所以这是不可能的。

I want to avoid any hidden state within the distribution object so that each call to this wrapper function only depends on the given arguments. (Potentially, each call to this function could take a different generator instance.) Ideally, I would make the distribution instance static const to ensure this; however, the distribution's operator() is not a const function, so this isn't possible.

是这样的:为了确保在分布中没有隐藏状态,是否需要和2)足够调用 reset()每次分配?例如:

My question is this: To ensure there is no hidden state within the distribution, is it 1) necessary and 2) sufficient to call reset() on the distribution each time? For example:

double normal(double mean, double sd, std::mt19937_64& generator)
{
    static std::normal_distribution<double> dist;
    dist.reset();
    return dist(generator, std::normal_distribution<double>::param_type(mean, sd));
}

(总体来说,我对 reset()函数的随机分布...我理解为什么发电机需要重置/补种,有时,为什么分配对象需要重置?)

(Overall, I'm confused about the purpose of the reset() function for the random distributions... I understand why the generator would need to be reset/reseeded at times, but why would the distribution object need to be reset?)

推荐答案


为了确保分发中没有隐藏状态,是1)
必要

To ensure there is no hidden state within the distribution, is it 1) necessary

是的。


每次对分配调用reset()?

and 2) sufficient to call reset() on the distribution each time?

是的。

你可能不想这样做。至少不是每一个电话。 std :: normal_distribution 是允许分布维护状态的poster-child。例如,流行的实现将使用 Box-Muller变换来一次计算两个随机数,但是你只回来其中一个,保存另一个下次你打电话。在下一次调用之前调用 reset()会导致分布丢弃这个已经有效的结果,并将算法的效率降低一半。

You probably don't want to do this though. At least not on every single call. The std::normal_distribution is the poster-child for allowing distributions to maintain state. For example a popular implementation will use the Box-Muller transformation to compute two random numbers at once, but hand you back only one of them, saving the other for the next time you call. Calling reset() prior to the next call would cause the distribution to throw away this already valid result, and cut the efficiency of the algorithm in half.

这篇关于我应该调用reset()在我的C ++ std随机分布,以清除隐藏状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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