random

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<iostream>
#include<random>
using namespace std;
template<typename T>
class RandGenerator {
public:
///用来存储随机数种子和每一轮生成的随机数,来计算下一个随机数
T a_;
///随机数生成器返回的随机数类型
using result_type = T;
explicit RandGenerator(T a) : a_(a) {}
///迭代
virtual constexpr T operator()() =0;

///定义最小和最大
//需要是static的
// virtual constexpr T min() =0;
// virtual constexpr T max() =0;
};
class RandGenerator1 : public RandGenerator<int> {
public:
RandGenerator1(int a) : RandGenerator<int>(a) {}
constexpr int operator()() {
///一个很快且可以用在并行的wangs hash
a_ = (a_ ^ 61) ^ (a_ >> 16);
a_ *= 9;
a_ = a_ ^ (a_ >> 4);
a_ *= 0x27d4eb2d;
a_ = a_ ^ (a_ >> 15);
return a_;
}
static constexpr int min() {
return 0;
}
static constexpr int max() {
return 100;
}
};
int main() {
///一个接近于真随机的从操作系统得来的随机数
random_device rd;
///调用这个随机数引擎生成一个初始种子
mt19937 rng(rd());
///限制范围
uniform_int_distribution<int> dist(0, 100);
uniform_real_distribution<double> dist2(0, 100);
normal_distribution<double> dist3(0, 100);
///也可以使用自定义的随机数生成引擎
RandGenerator1 rng1(0);
for (int i = 0; i < 10; ++i) {
cout << dist(rng1) << endl;
cout << dist(rng) << endl;
cout << dist2(rng) << endl;
cout << dist3(rng) << endl;
}
}

random
https://lhish.github.io/project/hide/random/
作者
lhy
发布于
2025年8月16日
许可协议