C++:高精度随机双精度数

C++: High Precision Random Double Numbers

本文关键字:双精度 随机 高精度 C++      更新时间:2023-10-16

这是本页答案的后续问题:

如何在C++中高精度生成随机双精度数?

#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 ;
}

答案很好用,但我很难意识到如何将此代码的输出放在双精度变量中而不是将其打印到 stdout 中。谁能帮忙?

谢谢。

您在实际精度和显示精度之间感到困惑 - 试试这个:

#include <iostream>
#include <random>
#include <iomanip>    
int main()
{
    std::random_device rd;
    std::mt19937 e2(rd());
    std::uniform_real_distribution<> dist(1, 10);
    double v = dist(e2);   // get a random double at full precision
    std::cout << std::fixed << std::setprecision(10) << v << std::endl;
                           // display random double with 10 digits of precision
    return 0;
}