How to generate random double numbers with high pr

2019-05-11 11:49发布

问题:

I am trying to generate a number of series of double random numbers with high precision. For example, 0.856365621 (has 9 digits after decimal).

I've found some methods from internet, however, they do generate double random number, but the precision is not as good as I request (only 6 digits after the decimal).

Thus, may I know how to achieve my goal?

回答1:

In C++11 you can using the <random> header and in this specific example using std::uniform_real_distribution I am able to generate random numbers with more than 6 digits. In order to see set the number of digits that will be printed via std::cout we need to use 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 ;
}

you can use std::numeric_limits::digits10 to determine the precision available.

std::cout << std::numeric_limits<double>::digits10 << std::endl;


回答2:

In a typical system, RAND_MAX is 231-1 or something similar to that. So your "precision" from using a method like:L

 double r = rand()/RAND_MAX;

would be 1/(2<sup>31</sup)-1 - this should give you 8-9 digits "precision" in the random number. Make sure you print with high enough precision:

 cout << r << endl;

will not do. This will work better:

 cout << fixed << sprecision(15) << r << endl; 

Of course, there are some systems out there with much smaller RAND_MAX, in which case the results may be less "precise" - however, you should still get digits down in the 9-12 range, just that they are more likely to be "samey".



回答3:

Why not create your value out of multiple calls of the random function instead?

For instance:

   const int numDecimals = 9;

   double result = 0.0;
   double div = 1.0;
   double mul = 1.0;
   for (int n = 0; n < numDecimals; ++n)
   {
      int t = rand() % 10;
      result += t * mul;
      mul *= 10.0;
      div /= 10.0;
   }    
   result = result * div;

I would personally try a new implementation of the rand function though or at least multiply with the current time or something..