我正在尝试生成一系列高精度的 double 随机数。例如,0.856365621(小数点后有 9 位)。
我从网上找了一些方法,但是,它们确实生成了双随机数,但是精度没有我要求的那么好(小数点后只有6位)。
因此,我可以知道如何实现我的目标吗?
最佳答案
在 C++11 中你可以使用 <random>
header并在此特定示例中使用 std::uniform_real_distribution
我能够生成超过 6
的随机数数字。为了查看设置将通过 std::cout
打印的位数我们需要使用 std::setprecision
:
#include <iostream>
#include <random>
#include <iomanip>
int main()
{
std::random_device rd;
std::mt19937 e2(rd());
std::uniform_real_distribution<> dist(1, 10);
for( int i = 0 ; i < 10; ++i )
{
std::cout << std::fixed << std::setprecision(10) << dist(e2) << std::endl ;
}
return 0 ;
}
你可以使用 std::numeric_limits::digits10
以确定可用的精度。
std::cout << std::numeric_limits<double>::digits10 << std::endl;
关于c++ - 如何在C++中生成高精度的随机 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18131612/