C++ - std::srand

C++ - std::srand

Defined in header <cstdlib> - 定义于头文件 <cstdlib>

1. std::srand

void srand (unsigned int seed);

Initialize random number generator - 初始化伪随机数生成器 (函数)

The pseudo-random number generator is initialized using the argument passed as seed.
伪随机数生成器使用 seed 传递的参数进行初始化。

For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.
对于调用 srand 时使用的每个 seed 值,可以期望伪随机数生成器在随后的 rand 调用中生成不同的结果序列。

Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.
具有相同 seed 的两个不同的初始化将在随后对 rand 的调用中生成相同的结果序列。

If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand orsrand.
如果将 seed 设置为 1,则将生成器重新初始化为其初始值,并产生与调用 rand orsrand 之前相同的值。

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>). This is distinctive enough for most trivial randomization needs.
为了生成类似随机的数字,通常将 srand 初始化为一些独特的运行时值,例如由 time 函数返回的值 (在头文件 <ctime> 中声明)。对于大多数琐碎的随机化需求而言,这足够独特。

Seeds the pseudo-random number generator used by std::rand() with the value seed.
以值 seed 播种 std::rand() 所用的伪随机数生成器。

If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1).
若在任何 srand() 的调用前使用 rand(),则 rand() 表现为如同它被以 srand(1) 播种。

Each time rand() is seeded with the same seed, it must produce the same sequence of values.
每次以同一 seed 播种 rand() 时,它必须产生相同的值数列。

srand() is not guaranteed to be thread-safe.
srand() 不保证为线程安全。

dereference [ˌdiːˈrefrəns]:v. 间接引用,间接访问,解引用
reallocate [ˌriːˈæləkeɪt]:v. 重新分配,再指派

Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), at the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.
通常来说,应该只播种一次伪随机数生成器,在程序开始处,任何到 rand() 的调用前。不应重复播种,或每次希望生成新一批伪随机数时重新播种。

Standard practice is to use the result of a call to time(0) as the seed. However, time() returns a time_t value, and time_t is not guaranteed to be an integral type. In practice, though, every major implementation defines time_t to be an integral type, and this is also what POSIX requires.
标准实践是使用以 time(0) 为种子调用的结果。然而 time() 返回 time_t 值,而不保证 time_t 是整数类型。尽管实践中,主流实现都定义 time_t 为整数类型,且此亦为 POSIX 所要求。

2. Parameters

seed
An integer value to be used as seed by the pseudo-random number generator algorithm.
伪随机数生成器算法将用作种子的整数值。

the seed value (种子值)

3. Return value

none - 无

4. Examples

srand(time(NULL));

使用当前时间进行伪随机数发生器的初始化。
time(NULL) 函数的返回值是作为 srand() 函数的参数。srand(time(NULL)); 以现在的系统时间作为随机数的种子来产生随机数,设置成 NULL 获得系统的当前时间,单位为秒。

4.1 std::srand

//============================================================================
// Name        : std::srand
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

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

int main()
{
	printf("First number: %d\n", rand() % 100);
	srand(time(NULL));
	printf("Random number: %d\n", rand() % 100);
	srand(1);
	printf("Again the first number: %d\n", rand() % 100);

	return 0;
}

Possible output:

First number: 83
Random number: 13
Again the first number: 83

4.2 std::srand

//============================================================================
// Name        : std::srand
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <cstdlib>
#include <iostream>
#include <ctime>

int main()
{
	std::srand(std::time(0)); // use current time as seed for random generator
	int random_variable = std::rand();
	std::cout << "Random value on [0 " << RAND_MAX << "]: " << random_variable << '\n';

	return 0;
}

Possible output:

Random value on [0 2147483647]: 631634451

5. Data races - 数据竞争

The function accesses and modifies internal state objects, which may cause data races with concurrent calls to rand or srand.
该函数访问和修改内部状态对象,这可能导致并发调用 rand or srand 的数据竞争。

Some libraries provide an alternative function of rand that explicitly avoids this kind of data race: rand_r (non-portable).
一些库提供了 rand 的替代功能,它明确避免了这种数据竞争:rand_r (不可移植)。

C++ library implementations are allowed to guarantee no data races for calling this function.
允许 C++ 库实现来保证调用此函数不会发生数据竞争。

6. Exception safety - 异常安全性

No-throw guarantee: this function never throws exceptions.
无抛出保证:此函数从不抛出异常。

assignment [ə'saɪnmənt]:n. 任务,布置,赋值

References

http://www.cplusplus.com/reference/cstdlib/srand/
https://en.cppreference.com/w/cpp/numeric/random/srand

发布了454 篇原创文章 · 获赞 1733 · 访问量 103万+

猜你喜欢

转载自blog.csdn.net/chengyq116/article/details/104429546