生成许多良好的均匀分布的随机数
Generating many, good, uniformly distributed random numbers
我正在 运行 分析具有随机权重的非常大的图。我知道使用 rand()
功能很差,所以我一直根据我所阅读的内容使用此功能来生成适当的随机数:
double randomZeroToOne()
{
random_device rd;
mt19937 mt(rd());
uniform_real_distribution<double> dist(0.0, 1.0);
double randomRealBetweenZeroAndOne = dist(mt);
return randomRealBetweenZeroAndOne;
}
每次我想在我的图中放置一个权重时,我都会调用这个函数并将它插入到我的邻接矩阵中。但是,我担心也许我正在使用一种缓慢的方法来生成这些数字。这对于小图来说效果很好,但我的大图非常慢(可能是其他原因减慢了它的速度,但我只是想仔细检查并学习正确的方法)。保持数字质量但尽可能快地生成它们的最佳方法是什么?
此外,如果您知道用快速、良好、均匀分布的随机数初始化已知大小的向量的方法,那就更好了(尽管我仍然对我的主要问题的答案感到好奇)。
编辑:
这是我新提出的解决方案:
#include <iostream>
#include <random>
#include<vector>
#include<iomanip>
#include<cmath>
using namespace std;
random_device rd;
mt19937 mt(rd());
uniform_real_distribution<double> dist(0.0, 1.0);
int main()
{
double randomRealBetweenZeroAndOne = dist(mt);
double anotherRandomRealBetweenZeroAndOne = dist(mt);
double anothernother = dist(mt);
vector<double> randoman(10,dist(mt));
cout << randomRealBetweenZeroAndOne << endl;
cout << anotherRandomRealBetweenZeroAndOne <<endl;
cout << anothernother <<endl;
}
如果您发现任何问题,请告诉我,尤其是当此函数将被多次调用时。
正如您在建议的解决方案中所建议的那样,您不想在每次需要随机数时都使用 std::random_device
并创建随机引擎。但我会避免使它们成为全局变量。我建议在函数中使用静态变量。它们仍然只初始化一次,所以它会一样快,但它们会更加封装:
double randomZeroToOne()
{
static mt19937 mt(std::random_device{}());
static uniform_real_distribution<double> dist(0.0, 1.0);
return dist(mt);
}
(请注意,同时从多个线程调用此函数是不安全的。如果这是一个要求,请将此处的 static
更改为 thread_local
。)
我正在 运行 分析具有随机权重的非常大的图。我知道使用 rand()
功能很差,所以我一直根据我所阅读的内容使用此功能来生成适当的随机数:
double randomZeroToOne()
{
random_device rd;
mt19937 mt(rd());
uniform_real_distribution<double> dist(0.0, 1.0);
double randomRealBetweenZeroAndOne = dist(mt);
return randomRealBetweenZeroAndOne;
}
每次我想在我的图中放置一个权重时,我都会调用这个函数并将它插入到我的邻接矩阵中。但是,我担心也许我正在使用一种缓慢的方法来生成这些数字。这对于小图来说效果很好,但我的大图非常慢(可能是其他原因减慢了它的速度,但我只是想仔细检查并学习正确的方法)。保持数字质量但尽可能快地生成它们的最佳方法是什么?
此外,如果您知道用快速、良好、均匀分布的随机数初始化已知大小的向量的方法,那就更好了(尽管我仍然对我的主要问题的答案感到好奇)。
编辑:
这是我新提出的解决方案:
#include <iostream>
#include <random>
#include<vector>
#include<iomanip>
#include<cmath>
using namespace std;
random_device rd;
mt19937 mt(rd());
uniform_real_distribution<double> dist(0.0, 1.0);
int main()
{
double randomRealBetweenZeroAndOne = dist(mt);
double anotherRandomRealBetweenZeroAndOne = dist(mt);
double anothernother = dist(mt);
vector<double> randoman(10,dist(mt));
cout << randomRealBetweenZeroAndOne << endl;
cout << anotherRandomRealBetweenZeroAndOne <<endl;
cout << anothernother <<endl;
}
如果您发现任何问题,请告诉我,尤其是当此函数将被多次调用时。
正如您在建议的解决方案中所建议的那样,您不想在每次需要随机数时都使用 std::random_device
并创建随机引擎。但我会避免使它们成为全局变量。我建议在函数中使用静态变量。它们仍然只初始化一次,所以它会一样快,但它们会更加封装:
double randomZeroToOne()
{
static mt19937 mt(std::random_device{}());
static uniform_real_distribution<double> dist(0.0, 1.0);
return dist(mt);
}
(请注意,同时从多个线程调用此函数是不安全的。如果这是一个要求,请将此处的 static
更改为 thread_local
。)