如何在C ++中生成高精度的随机双精度数字? [英] How to generate random double numbers with high precision in C++?

查看:343
本文介绍了如何在C ++中生成高精度的随机双精度数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图生成一系列的高精度的双随机数。例如,0.856365621(十进制后有9位数字)。

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

我从互联网上找到了一些方法,但是它们会产生双重随机数, (只有小数点后6位)。

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?

推荐答案

在C ++ 11中,您可以使用 < random> ,在此具体示例中使用 std :: uniform_real_distribution 我可以生成随机数超过 6 位数。为了设置将通过 std :: cout 打印的数字位数,我们需要使用 std :: setprecision

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

您可以使用 std :: numeric_limits :: digits10 p>

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

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

这篇关于如何在C ++中生成高精度的随机双精度数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆