在 C++ 中生成随机数的最佳方法是什么? [英] What is the best way to generate random numbers in C++?

查看:36
本文介绍了在 C++ 中生成随机数的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生成随机数的最佳方法是什么?

What is the best way to generate random numbers?

推荐答案

当且仅当:

  • 您不是在寻找完美的一致性"或

  • 您没有 C++11 支持,甚至没有 TR1(因此您别无选择)

  • 那么您可能会考虑使用以下 C 风格的解决方案,其中(为了这个社区的声誉~请参阅 rand() 被认为有害) 以删除线字体书写:

    then you might consider using the following C-style solution, which (for the sake of the reputation of this community ~ see rand() Considered Harmful) is written in strike-through font:

    这是一个简单的 C 风格的函数,它从 minmax 的区间生成随机数,包括.这些数字似乎非常接近均匀分布.

    Here's the simple C-style function that generates random number from the interval from min to max, inclusive. Those numbers seem to be very close to being uniformly distributed.

    int irand(int min, int max) {
        return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min;
    }
    

    并且在使用之前不要忘记调用srand:

    int occurences[8] = {0};
    
    srand(time(0));
    for (int i = 0; i < 100000; ++i)
        ++occurences[irand(1,7)];
    
    for (int i = 1; i <= 7; ++i)
        printf("%d ", occurences[i]);
    

    输出:14253 14481 14210 14029 14289 14503 14235

    还可以看看:
    生成范围内的随机数?
    在整个范围内均匀生成随机数
    找些时间,至少观看上述 视频的前 11 分钟

    使用 只是就像 Kerrek SB 已经指出的那样.

    use <random> just like it was pointed out by Kerrek SB already.

    这篇关于在 C++ 中生成随机数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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