随机数算法

发布时间 2023-11-05 21:41:58作者: 月光幻影

$ rand() $

  • 范围:0 - 32767

  • 不是真正的随机,只是因为周期很长,看起来像

  • 如果不进行初始化,每次输出的结果是相同的

# include <bits/stdc++.h>
using namespace std;

signed main(){
	freopen("1.out", "w", stdout);
	for(int i = 1; i <= 10; i++){
		cout << rand() << " ";
	}
}
第一次:41 18467 6334 26500 19169 15724 11478 29358 26962 24464 
第二次:41 18467 6334 26500 19169 15724 11478 29358 26962 24464 
  • 使用 $ srand() $ 初始化
# include <bits/stdc++.h>
using namespace std;

signed main(){
	freopen("1.out", "w", stdout);
	cout << time(0) << "time\n";
	srand(time(0));
	for(int i = 1; i <= 10; i++){
		cout << rand() << " ";
	}
}
第一次:
1699190385time
6040 29445 28556 23486 1862 13319 24738 16235 15802 22910 
第二次:
1699190429time
6184 10855 28148 927 29720 22256 30613 18506 21416 14539 

Xor_shift

1.初始化就是设定随机种子,不同的设定产生不同的伪随机序列

2.异或和移位每次都在上一次产生的值上产生新的值,因为在很大的值中舍弃了一些值,所以每次产生的值看起来就象是随机值,也就是伪随机数

unsigned i64 Xor_shift(unsigned i64 x){
    x ^= x >> 13;
    x ^= x << 7;
    x ^= x >> 17;
    return x;
}
  • 13,7,17或13,5,17或26,15,17均可,但不是任意三个数都行
以 srand() 的第二组输出作为种子
789550 1382764 3577452 117791 3832198 2830311 3914891 2387034 2721470 1859012 

mt19937

  • 范围:$ unsigned $ \(~\) $ long $ \(~\) $ long $

  • 假随机,只是相比 $ rand() $ 周期更长

# include <bits/stdc++.h>
# define i64 long long
using namespace std;

signed main(){
	freopen("1.in", "w", stdout);
	mt19937 mt_rand(time(0));
	for(int i = 1; i <= 10; i++){
		cout << mt_rand() << " ";
	}
}
471076068 2678204948 2173609593 3795441098 2911085438 2517774531 2072600482 3361426292 3805571956 4164973925