跳到正文

算法·理论

随机化小tips

movefast约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年7月8日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 2 分钟

版本

  1. v1当前

一种比较好的随机化数

C++
mt19937_64(chrono::steady_clock::now().time_since_epoch().count())

rand() 不建议使用

mt19937 是 unsigned int 范围的, mt19937_64 是unsigned long long,初始化如 mt19937 ran(种子)

还是复制一下吧

lnw143%%%

使用random_device作为种子

新建mt19937随机数

用uniform_int_distribution(整数范围)、uniform_real_distribution(实数范围)限定范围

C++
// C++11
#include<cstdio>
#include<random>
#include<chrono>
using namespace std;
#define clock() (chrono::steady_clock::now())
const int n=1e7;
int a[11];
int main() {
	mt19937 rnd(random_device{}());
	uniform_int_distribution<int> int_dist(1,10); // 整数
	uniform_real_distribution<double> real_dist(1,10); // 实数
	printf("%d %lf\n",int_dist(rnd),real_dist(rnd));
	auto st=clock();
	for(int i=1; i<=n; ++i)
		++a[int_dist(rnd)];
	printf("int_dist costed time: %.3lfs\n",chrono::duration<double>(clock()-st).count());
	for(int i=1; i<=10; ++i)
		printf("%d%c",a[i]," \n"[i==10]);
	st=clock();
	for(int i=1; i<=n; ++i)
		real_dist(rnd);
	printf("real_dist costed time: %.3lfs\n",chrono::duration<double>(clock()-st).count());
	return 0;
}
原文