JOURNAL ENTRY

对于 Intel CPU 下的 C++ 真随机数

C++ 通用随机数

调用随机数的时候只需要用 rand()

但是需要引入 stdlib.h

而且需要在主函数中调用 srand(),来设置种子,示例:

/* ... */
int main() {
    srand(time(0));
    /* ... */
}

但是这样有概率会出现随机数不均匀的情况

Rand 库

这个是一个 C++ 提供的随机数库。

#include <bits/stdc++.h>
using namespace std;
int main() {
    random_device rd; 
    mt19937 gen(rd()); 
    uniform_int_distribution<> distrib(1, 6);
    cout << distrib(gen) << ' ';
}

调用 CPU 的随机数函数

#include <iostream>
#include <immintrin.h>

int main() {
    unsigned int x;

    for (int i = 0; i <= 10000; i ++) {
        if (_rdrand32_step(&x)) {
            std::cout << "Random:" << x << "\n";
        } else {
            std::cerr << "Error\n";
        }
    }
}

但是注意需要添加编译命令

-std=c++14 -m32 -mrdrnd
END OF ARTICLE

继续阅读

评论 (0)

取消