2013-10-04 50 views
1

我即將生成一個正態分佈的僞隨機數組。據我所知性病庫提供下面的代碼爲:使用用戶定義的隨機生成器運行std :: normal_distribution

std::random_device rd; 
std::mt19937 gen(rd()); 
std::normal_distribution<> d(mean,std); 
... 
double number = d(gen); 

的問題是,我想用一個Sobol」準隨機序列,而不是梅森 倍捻機僞隨機生成。所以,我的問題是: 是否有可能運行std :: normal_distribution與用戶定義的隨機生成器(與Sobol'準隨機序列發生器在我的情況)?


更多細節:我有一個叫RandomGenerators類,它是用來生成Sobol」準隨機數:

RandomGenerator randgen; 
double number = randgen.sobol(0,1); 

回答

5

是的,這是可能的。只是使其符合至均勻的隨機數生成器的要求(§26.5.1.3第2和第3):

2所述的類G滿足的均勻隨機數發生器 的要求,如果在表中示出的表達式116是有效的並且 指示了語義,並且如果G也滿足本節的所有其他要求 。在該表和在整個本節:

一個)TG’s associated result_type`命名的類型,以及

B)gG的值。

表116 - 均勻隨機數發生器要求

Expression  | Return type | Pre/post-condition   | Complexity 
---------------------------------------------------------------------- 
G::result_type | T  | T is an unsigned integer | compile-time 
       |    | type (§3.9.1).    | 
---------------------------------------------------------------------- 
g()   | T  | Returns a value in the  | amortized constant 
       |    | closed interval   | 
       |    | [G::min(), G::max()].  | 
---------------------------------------------------------------------- 
G::min()  | T  | Denotes the least value | compile-time 
       |    | potentially returned by | 
       |    | operator().    | 
---------------------------------------------------------------------- 
G::max()  | T  | Denotes the greatest value | compile-time 
       |    | potentially returned by | 
       |    | operator().    | 

3下面的關係應保持:G::min() < G::max()

+1

謝謝Martinho!這種方法運作良好。我找到了一個很好的例子,在這裏[http://www.sitmo.com/article/parallel-random-number-generator-in-c/]。 –

1

這裏有個小心點 - 當我實現這個時,我遇到了一個大問題。看來,如果max()/ min()/ operator()的返回類型不是64位,那麼分配將重新採樣。我的(無符號)32位Sobol實現每次偏離採樣兩次,從而破壞數字的屬性。該代碼再生:

#include <random> 
#include <limits> 
#include <iostream> 
#include <cstdint> 

typedef uint32_t rng_int_t; 

int requested = 0; 
int sampled = 0; 

struct Quasi 
{ 
    rng_int_t operator()() 
    { 
    ++sampled; 
    return 0; 
    } 

    rng_int_t min() const 
    { 
    return 0; 
    } 

    rng_int_t max() const 
    { 
    return std::numeric_limits<rng_int_t>::max(); 
    } 
}; 

int main() 
{ 
    std::uniform_real_distribution<double> dist(0.0,1.0); 

    Quasi q; 

    double total = 0.0; 
    for (size_t i = 0; i < 10; ++i) 
    { 
    dist(q); 
    ++requested; 
    } 
    std::cout << "requested: " << requested << std::endl; 
    std::cout << "sampled: " << sampled << std::endl; 
} 

輸出(使用克++ 5.4):

requested: 10 
sampled: 20 

並且即使當使用-m32編譯。如果將rng_int_t更改爲64位,問題就會消失。我的解決方法是將32位值粘成的返回值的最顯著位,e.g

return uint64_t(val) << 32; 
相關問題