rand() 和 srand() 给出了奇怪的相似结果。 rand() 的返回非常相似

2024-01-05

这是一个看似常见的问题,所以我希望我听起来不是多余的。但是从 rand() 返回的范围应该在 0 和 RAND_MAX 之间,但是,当我执行一个非常简单的 rand 语句时,我总是得到一个非常小的范围内的返回值。

该范围类似于 1,4XX,XXX,XXX。我认为这可能是一个时钟问题,所以我等了三十分钟,但仍然得到相同范围内的数字。

以下是二十分钟前的一些示例输出:

Matthews-Macbook-Pro:Data_Structures matthewwright$ ./main
1439810968
80
Matthews-Macbook-Pro:Data_Structures matthewwright$ ./main
1439827775
29
Matthews-Macbook-Pro:Data_Structures matthewwright$ ./main
1439827775
29
Matthews-Macbook-Pro:Data_Structures matthewwright$ ./main
1439844582
78
Matthews-Macbook-Pro:Data_Structures matthewwright$ ./main
1439878196
29
Matthews-Macbook-Pro:Data_Structures matthewwright$ ./main
1439895003
78

这是刚才的输出示例:

Matthews-Macbook-Pro:Data_Structures matthewwright$ ./main
1456483512
78
Matthews-Macbook-Pro:Data_Structures matthewwright$ ./main
1456500319
80
Matthews-Macbook-Pro:Data_Structures matthewwright$ ./main
1456500319
80
Matthews-Macbook-Pro:Data_Structures matthewwright$ ./main
1456517126
29
Matthews-Macbook-Pro:Data_Structures matthewwright$ ./main
1456533933
78

我知道 rand() 并不完美,但这看起来太相似而不是正确的。如果范围是 0 - RAND_MAX,则返回的每个数字都在同一范围内似乎很奇怪。

这是我正在测试的代码:

#include <iostream>
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main(int argc, char const *argv[])
{
    /* declarations */
    srand(time(NULL));

    std::cout << std::rand() << std::endl;
    std::cout << std::rand()%100 << std::endl;
    return 0;
}

我认为我不需要所有这些 #include 语句,但我看到其他人使用它们,所以我将它们包含在内,以防它会影响我的输出,但事实并非如此。

Edit

所以@Mgetz 和@Curious 提供的链接非常有帮助。以巩固,

信息页面:http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution

超级有用的讲座(真正的,观看这个):https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

我把我在讲座中听到的内容总结在自己的笔记上,这样如果我忘记了,就不用再重新研究了。我没有在这里编写代码,大部分代码都在上面链接的“信息页面”中。大多数评论包含讲座中的信息,尽管不是讲座中的逐字内容。再次,我真的建议观看。它内容丰富,信息丰富。

#include <iostream>
#include <random>

int main(int argc, char const *argv[])
{
    /* https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful */

    /* Randomness Verson 1 : Deterministic */
    std::mt19937 mt(1234);
    std::uniform_int_distribution<int> dist(0,127);
    /* Default is int, but we could specify others.
     * The range is [inclusive, inclusive]
     * 
     * Above is Mersenne Twister RNG. It is deterministic, meaning we can get the same result
     * if we use "std::mt19937 mt(1234)"; or something like that. This could be useful for some
     * people (He mentions games, some experiments, et cetera). It is stupid fast.
     * 
     * However, it isn't cryptographically secure, but it pretty random as random goes. If you
     * track the output though, you could guess the next numbers, so don't use it for anything
     * secure.
     */

    /* Randomness Verson 2 */
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<int> dis(0, 127); // Inclusive
    /* This is not reproducible. This is not deterministic.
     * "Possibly Crypto-secure." Seems like using Random Device makes this near perfect random,
     * assuming some conditions. I'm not a man who's written security software, and if you are 
     * writing security software, I assume you're not looking at StackOverflow to figure out how
     * to do random numbers. The way he talked about it in the lecture made this seem much more 
     * secure, but I'm not sure what I'm talking about when it comes to these things
     */

    for (int i = 0; i < 3; ++i)
    {
        /* Below would output the pure Mersenne Twister output, deterministic. This seems to
         * be pretty random, but it isn't totally random. */
        std::cout << dist(mt) << " ";

        /* And below would output the random device output. This should be slower, but
         * more truly random. */

        //Use dis to transform the random unsigned int generated by gen into an int in [1, 6]
        std::cout << dis(gen) << " ";

        std::cout<< std::endl;
    }
}

使用模运算符会给生成的“随机数”带来一定程度的偏差。进一步做好工作rand()函数是实现定义的,不遵循跨平台的标准算法。

考虑使用更现代的 C++11 随机数生成功能,这些功能使用标准的广泛接受的随机数生成算法,跨平台工作相同(当然给定相同的种子)。

请参阅以下示例std::uniform_int_distribution 的 cppreference 页面 http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> dis(1, 6);

    for (int n=0; n<10; ++n)
        //Use dis to transform the random unsigned int generated by gen into an int in [1, 6]
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

这是 Stephan Levavej 的精彩演讲的链接,该演讲更深入地探讨了这一点https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

rand() 和 srand() 给出了奇怪的相似结果。 rand() 的返回非常相似 的相关文章

  • 如何从该 Voronoi 图数据中获取单元格字典?

    使用找到的voronoi delaunay图生成库在这个节目中 http sourceforge net projects mapmanager 这是基于 财富 最初的实施他的算法 http en wikipedia org wiki Fo
  • c++11 正则表达式比 python 慢

    嗨我想了解为什么以下代码使用正则表达式进行分割字符串分割 include
  • 如何使用 ASP.NET MVC 进行 HTTP 调用?

    我正在尝试做的事情 我试图练习进行 HTTP 调用 如果这就是它的名字 来自一个简单的 ASP NET MVC Web 应用程序 为此 我尝试从以下位置获取天气详细信息打开天气地图 http openweathermap org appid
  • 用 C# 启动 Windows 服务

    我想启动一个刚刚安装的Windows服务 ServiceBase ServicesToRun if bool Parse System Configuration ConfigurationManager AppSettings RunSe
  • C++ 模板中的名称查找

    我有一些 C 代码 如果没有 fpermissive 选项 就无法再编译 这是我无法分享的专有代码 但我认为我已经能够提取一个简单的测试用例来演示该问题 这是 g 的输出 template eg cpp In instantiation o
  • asp.net c# 将数据集中的数据转换为电子邮件正文?

    从数据集到电子邮件正文的最佳方式是什么 我有一个 net 控制台应用程序 用于根据存储过程的结果发送电子邮件通知 并且想知道如何最好地从 SQL 数据转到电子邮件正文 带有颜色和字体的 html 正文是最好的 但纯文本也可以 thanks
  • 如何在 MFC 中调整对话框大小时移动控件?

    我已经在 MFC 中创建了对话框视图 从下图中可以清楚地看到 如滑块控件和编辑框等 当我调整对话框大小时 这些控件不会移动 在此输入图像描述 https i stack imgur com 7OxAK jpg 我想移动控件以适应对话框 但不
  • 隐式方法组转换陷阱

    我想知道为什么给定代码的输出 在 LinqPad 中执行 void Main Compare1 Action Main Dump Compare2 Main Dump bool Compare1 Delegate x return x Ac
  • 泛型与接口的实际优势

    在这种情况下 使用泛型与接口的实际优势是什么 void MyMethod IFoo f void MyMethod
  • 我们如何将数据从一个打开的表单传递到另一个打开的表单?

    winform中如何将数据从一个窗体传递到另一个打开的窗体 在 Windows 应用程序中 一个窗体打开另一个窗体 当我在父表单中输入一些数据时 这些数据将立即反映在另一个子表单中 这将如何发生 取决于你想要多花哨 最简单的方法就是直接调用
  • 如何从 List 中的字符串中删除数字/数字?

    我有一个字符串列表 List
  • 异步方法中的异常未被捕获

    下面的代码没有捕获我的OperationCancelEException 它是通过调用抛出的ct ThrowIfCancellationRequested public partial class TitleWindow Window IA
  • 如何防止字符串被截留

    我的理解 可能是错误的 是 在 C 中 当你创建一个字符串时 它会被实习到 实习生池 中 这保留了对字符串的引用 以便多个相同的字符串可以共享操作内存 但是 我正在处理很多很可能是唯一的字符串 一旦完成每个字符串 我需要将它们从操作内存中完
  • 套接字:监听积压并接受

    listen sock backlog 在我看来 参数backlog限制连接数量 这是我的测试代码 server initialize the sockaddr of server server sin family AF INET ser
  • Create CFrameWnd 给出了第一次机会异常——为什么?

    我正在尝试使用基于 CFrameWnd 的代码编写一个简单的 MFC 应用程序 该应用程序在可滚动窗口中绘制 下面的代码改编自 Prosise Programming Windows with MFC 第 2 版 第 89ff 页 当我在调
  • C# 的空条件委托调用线程安全吗? [复制]

    这个问题在这里已经有答案了 这就是我一直以来编写事件引发者的方式 例如属性更改 public event PropertyChangedEventHandler PropertyChanged private void RaisePrope
  • 我应该使用多个 HttpClient 来进行批量异步 GET 请求吗?

    我有一个场景 我需要在尽可能短的时间内发出大量 GET 请求 想想大约 1000 个 我知道通常最好保留一个客户端并尽可能重用它 Create Single HTTP Client HttpClient client new HttpCli
  • win32 API 和 .NET 框架之间的选择

    我必须开发一个适用于 Windows 的应用程序 该应用程序将能够通过网络摄像头识别手势来控制鼠标 我将使用 vc 2008 进行开发 但我很困惑是使用 NET 框架还是核心 win32 API 性能对于我的应用程序非常重要 根据 Ivor
  • 如何分析 VSCode 中函数的性能

    我用 C Golang 编写了一个程序 如何找到占用最高 CPU 周期的函数 目的是提高正在执行的程序的性能 2021 年 10 月 金香儿哈娜 https github com hyangah宣布 tweet https twitter
  • double 类型的静态类成员的常量表达式初始值设定项

    在 C 11 和 C 14 中 为什么我需要constexpr在下面的代码片段中 class Foo static constexpr double X 0 75 而这会产生编译器错误 class Foo static const doub

随机推荐