c++隨機數引擎

/**
 * 做者: cwl
 * 描述: c++ 隨機數引擎生成隨機數
 * */
#include <bits/stdc++.h>

using namespace std;

template <typename T>
void printVector(std::vector<T> &vec, int index = 0) {
    cout << "[" << index << "] ";
    for(auto &iter: vec) {
        cout << "" << iter << " ";
    }
    cout << endl;
}

int main()
{

    //隨機數廣泛是經過線性同餘運算產生的爲僞隨機,以前咱們用rand() % mod
    //這裏咱們嘗試隨機數引擎

    auto randomVectorUnsigned = [](int count) -> vector<unsigned int> {
        int random_seed = time(0);
        //能夠用下面兩種方式設置seed
        default_random_engine e(random_seed);
        e.seed(random_seed);
        //隨機數
        uniform_int_distribution<unsigned int>u(0, 100);
        vector<unsigned int>vec;
        for(auto i = 1; i <= count; ++i) {
            vec.push_back(u(e));
        }
        return vec;
    };

    vector<unsigned int> test_int = randomVectorUnsigned(10);
    printVector(test_int, 1);

    auto randomVectorDouble = [](int count) -> vector<double> {
        int random_seed = time(0);
        //能夠用下面兩種方式設置seed
        default_random_engine e(random_seed);
        e.seed(random_seed);
        //隨機數
        uniform_real_distribution<double>u(0, 10);
        vector<double>vec;
        for(auto i = 1; i <= count; ++i) {
            vec.push_back(u(e));
        }
        return vec;
    };
    vector<double> test_double = randomVectorDouble(10);
    printVector(test_double, 2);

    //生成非均勻的隨機數

    auto randomVector = [](int count) -> vector<double> {
        int random_seed = time(0);
        //能夠用下面兩種方式設置seed
        default_random_engine e(random_seed);
        e.seed(random_seed);
        //隨機數
        normal_distribution<> n(4, 1.5); //均值4,標準差1.5;
        vector<double>vec;
        for(auto i = 1; i <= count; ++i) {
            vec.push_back(n(e));
        }
        return vec;
    };
    vector<double> test = randomVector(10);
    printVector(test);


    return 0;
}
相關文章
相關標籤/搜索