使用rand()/(RAND_MAX +1) [英] Using rand()/(RAND_MAX +1)

查看:735
本文介绍了使用rand()/(RAND_MAX +1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个使用rand()的问题:
rand()/(RAND_MAX + 1.0)

i have problem with this use of rand(): rand() / (RAND_MAX + 1.0)

我知道简单 rand()(like rand()%100 + 1)但是我不明白完整的句子句子rand()/(RAND_MAX + 1.0)

I know the "simple" use for rand() (like rand() %100 + 1) but i don't understand what full sentence sentence rand() / (RAND_MAX + 1.0)

推荐答案

简单来说, rand()/(RAND_MAX + 1.0)生成一个0(包括)和1.0(不包括)之间的浮点随机数。更准确地说(请参阅 http://en.cppreference.com/w/cpp/numeric / random / RAND_MAX 作为参考),返回的最大数目可以是RAND_MAX /(RAND_MAX + 1.0)。然而,在蒙特卡罗模拟的上下文中,关于这样的随机数生成器有几个重要点,因为RAND_MAX通常是32767:

Simply speaking, rand() / (RAND_MAX + 1.0) generates a floating-point random number between 0 (inclusive) and 1.0 (exclusive). More precisely (see http://en.cppreference.com/w/cpp/numeric/random/RAND_MAX for reference), the maximal number returned can be RAND_MAX / (RAND_MAX + 1.0). However, in the context of Monte-Carlo simulations there are several important points about such random number generator because RAND_MAX is usually 32767:


  1. 可以生成的不同随机数字太小:32768.通常他们运行更多的蒙特卡罗模拟 - 数百万或数十亿 - 但这样有限的随机数生成器无意义运行超过32768模拟

  2. 生成的数字太粗糙:您可以获得1/32768,2/32768,3/32768,但从不间断。

  3. 随机数状态有限发电机发动机:在生成RAND_MAX个随机数字之后,实施通常开始重复相同的随机数序列。

由于上述限制rand(),一个更好的选择为蒙特卡罗模拟生成随机数将是以下代码段(类似于 http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution ):

Due to the above limitations of rand(), a better choice for generation of random numbers for Monte-Carlo simulations would be the following snippet (similar to the example at http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution ):

#include <iostream>
#include <random>
#include <chrono>

int main()
{
    std::mt19937_64 rng;
    // initialize the random number generator with time-dependent seed
    uint64_t timeSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
    std::seed_seq ss{uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed>>32)};
    rng.seed(ss);
    // initialize a uniform distribution between 0 and 1
    std::uniform_real_distribution<double> unif(0, 1);
    // ready to generate random numbers
    const int nMonteCarloSimulations = 10;
    for (int i = 0; i < nMonteCarloSimulations; i++)
    {
        double currentRandomNumber = unif(rng);
        std::cout << currentRandomNumber << std::endl;
    }
    return 0;
}

这篇关于使用rand()/(RAND_MAX +1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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