简体   繁体   English

C ++中用于函数rand()的公式

[英]Formula used for function rand() in c++

I want to know what is the formula used for generating random numbers using the rand() function in C++. 我想知道使用C ++中的rand()函数生成随机数的公式是什么。 At first I though it would return random numbers every time, but it does not. 起初我虽然每次都会返回随机数,但是不会。

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    cout << "Hello world!" << endl;

    srand(9865);
    cout << rand() << "\n";
    return 0;
}

Here I thought that, maybe because of given seed number and that unknown formula, it will be showing same number. 在这里我想,也许是由于给定的种子数量和未知的公式,它会显示相同的数量。

But, when i removed "srand(9865);" 但是,当我删除“ srand(9865)”时, and execute several times it is showing only "41" as output. 并执行几次,仅显示“ 41”作为输出。 Please explain me what is all going on here. 请给我解释一下这是怎么回事。

From http://linux.die.net/man/3/rand 来自http://linux.die.net/man/3/rand

"If no seed value is provided, the rand() function is automatically seeded with a value of 1. ", and "..These sequences are repeatable by calling srand() with the same seed value. " “如果未提供种子值,则rand()函数将自动以值1,“和”作为种子。通过调用具有相同种子值的srand(),这些序列是可重复的。

You have to seed your random function with a non static seed every time. 您每次都必须使用非静态种子为随机函数播种。 One simple but not so accurate solution is to seed it with the clock: 一种简单但不太准确的解决方案是随时钟播种它:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    cout << "Hello world!" << endl;

    srand(time(NULL));
    cout << rand() << "\n";
    return 0;
}

The library specifications don't dictate the formula for the random number generator (it is up to the implementation). 库规范没有规定随机数生成器的公式(取决于实现)。 The only things specified are that things can be controlled via srand for consistent pseudo-random generation: 指定的唯一的东西是东西可以通过控制srand的一致伪随机生成:

In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header <ctime>). 为了生成类似随机数的值,通常将srand初始化为一些与众不同的运行时值,例如函数time返回的值(在标头<ctime>中声明)。 This is distinctive enough for most trivial randomization needs. 对于大多数琐碎的随机化需求而言,这足够独特。

So: 所以:

  1. If you initialize srand with a given seed, the following rand calls will be consistent across runs. 如果使用给定的种子初始化srand ,则以下rand调用在各个运行之间将保持一致。

  2. If you initialize srand with a time-based seed, the following rand calls will almost surely be different across runs. 如果您使用基于时间的种子初始化srand ,则以下rand调用在运行中几乎肯定会有所不同。

  3. If you do not initialize srand , the following calls to rand will use the default initial seed. 如果不初始化srand ,则以下对rand调用将使用默认的初始种子。


Note that in contemporary C++, you should avoid using these ancient functions. 请注意,在当代C ++中,应避免使用这些古老的函数。 See the answers to this question . 请参阅此问题的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM