How to generate random double numbers with high pr

2019-05-11 12:11发布

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?

3条回答
Fickle 薄情
2楼-- · 2019-05-11 12:18

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楼-- · 2019-05-11 12:34

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..

查看更多
我只想做你的唯一
4楼-- · 2019-05-11 12:42

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;
查看更多
登录 后发表回答