使用Boost随机基础设施,但如何轻松更换组件(例如底层生成器)

Using Boost random infrastructure but how to easily replace a component (say the underlying generator)?

本文关键字:组件 基础设施 随机 Boost 何轻松 使用      更新时间:2023-10-16

我的用例是,比如说,课堂使用。

Boost随机基础设施已经存在,我尽量避免NIH syndrom。但是比方说,我想

1-研究各种PRNG的性质(好吧,比如缺陷)及其对正态(或其他分布)变量生成的影响。如何做到这一点并仍然保留生成一大堆发行版的其他 Boost 功能?

2-使用Boot(例如Mersenne Twister)生成器并测试生成其他发行版(例如普通发行版)的各种方法。

有没有一种简单而通用的方法可以对任何 Boost 随机基础设施组件进行这种直接替换,并且仍然能够使用其余组件?

Boost.Random 中随机性的基本来源称为"生成器"。Boost 中提供了几个,但我认为您没有理由不能使用自己的。

boost文档中的示例展示了如何创建生成器对象,然后将其传递给发行版以获取一系列数字。

--后--

这是我开发的一个基本生成器(基于 rand48):

#include <iostream>
#include <boost/random.hpp>
class my_rand {
public:
//  types
    typedef boost::uint32_t result_type;
//  construct/copy/destruct
    my_rand () : next_ ( 0 ) {}
    explicit my_rand( result_type x ) : next_ ( x ) {}
//  public static functions
    static uint32_t min() { return 0; }
    static uint32_t max() { return 10; }
    // public member functions
    void seed() { next_ = 0; }
    void seed(result_type x) { next_ = x; }
//  template<typename It> void seed(It &, It);
//  template<typename SeedSeq> void seed(SeedSeq &);
    uint32_t operator()() {
        if ( ++next_ == max ())
            next_ = min ();
        return next_;
        }
    void discard(boost::uintmax_t) {}
//  template<typename Iter> void generate(Iter, Iter);
    friend bool operator==(const my_rand & x, const my_rand &y);
    friend bool operator!=(const my_rand & x, const my_rand &y);
    // public data members
    static const bool has_fixed_range;
private:
    result_type next_;
};
bool operator==(const my_rand & x, const my_rand &y) { return x.next_ == y.next_; }
bool operator!=(const my_rand & x, const my_rand &y) { return x.next_ != y.next_; }
const bool my_rand::has_fixed_range = true;
int main ( int, char ** ) {
//  boost::random::mt19937 rng;
    my_rand rng;
    boost::random::uniform_int_distribution<> six(1,6);
    for ( int i = 0; i < 10; ++i )
        std::cout << six(rng) << std::endl;
    return 0;
    }

显然,输出不是随机的。但它确实与Boost.Random基础设施互操作。