Random function in cpp

rand

Returns a pseudo-random integral number in the range between 0 and RAND_MAX .

This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand .

A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

v1 = rand() % 100; // v1 in the range 0 to 99 v2 = rand() % 100 + 1; // v2 in the range 1 to 100 v3 = rand() % 30 + 1985; // v3 in the range 1985-2014 

Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely).

C++ supports a wide range of powerful tools to generate random and pseudo-random numbers (see for more info).

Parameters

Return Value

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* rand example: guess the number */ /* printf, scanf, puts, NULL */ /* srand, rand */ /* time */ int main () < int iSecret, iGuess; /* initialize random seed: */ srand (time(NULL)); /* generate secret number between 1 and 10: */ iSecret = rand() % 10 + 1; do < printf ("Guess the number (1 to 10): "); scanf ("%d",&iGuess); if (iSecret"The secret number is lower"); else if (iSecret>iGuess) puts ("The secret number is higher"); > while (iSecret!=iGuess); puts ("Congratulations!"); return 0; >

In this example, the random seed is initialized to a value representing the current time (calling time ) to generate a different value every time the program is run.

 Guess the number (1 to 10): 5 The secret number is higher Guess the number (1 to 10): 8 The secret number is lower Guess the number (1 to 10): 7 Congratulations! 

Compatibility

In C, the generation algorithm used by rand is guaranteed to only be advanced by calls to this function. In C++, this constraint is relaxed, and a library implementation is allowed to advance the generator on other circumstances (such as calls to elements of ).

Читайте также:  Java read file with fileinputstream

Data races

The function accesses and modifies internal state objects, which may cause data races with concurrent calls to rand or srand .

Some libraries provide an alternative function that explicitly avoids this kind of data race: rand_r (non-portable).

C++ library implementations are allowed to guarantee no data races for calling this function.

Источник

std:: rand

Returns a pseudo-random integral value from the range [ ​ 0 ​ , RAND_MAX ] .

std::srand() seeds the pseudo-random number generator used by rand() . If rand() is used before any calls to std::srand() , rand() behaves as if it was seeded with std:: srand ( 1 ) .

Each time rand() is seeded with std::srand() , it must produce the same sequence of values on successive calls.

Other functions in the standard library may call rand . It is implementation-defined which functions do so.

It is implementation-defined whether rand() is thread-safe.

Contents

[edit] Parameters

[edit] Return value

Pseudo-random integral value between ​ 0 ​ and RAND_MAX .

[edit] Notes

There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls).

rand() is not recommended for serious random-number generation needs. It is recommended to use C++11’s random number generation facilities to replace rand(). (since C++11)

[edit] Example

#include #include #include int main() { std::srand(std::time(nullptr)); // use current time as seed for random generator int random_variable = std::rand(); std::cout  "Random value on [0, "  RAND_MAX  "]: "  random_variable  '\n'; // roll 6-sided dice 20 times for (int n = 0; n != 20; ++n) { int x = 7; while (x > 6) x = 1 + std::rand() / ((RAND_MAX + 1u) / 6); // Note: 1 + rand() % 6 is biased std::cout  x  ' '; } }
Random value on [0, 2147483647]: 726295113 6 3 6 2 6 5 6 3 1 1 1 6 6 6 4 1 3 6 4 2

Источник

rand

Создает псевдослучайное число. Доступна более защищенная программно версия этой функции; см. раздел rand_s . Числа, созданные , rand не являются криптографически безопасными. Для более безопасного создания случайных чисел криптографически используйте rand_s функции или , объявленные в стандартной библиотеке C++ в .

Синтаксис

Возвращаемое значение

Функция rand возвращает псевдослучайное число, как описано выше. Ошибка не возвращается.

Комментарии

Функция rand возвращает псевдослучайное целое число в диапазоне от 0 до RAND_MAX (32767). Используйте функцию srand для заполнения генератора псевдослучайных чисел перед вызовом rand .

Функция rand создает хорошо известную последовательность и не подходит для использования в качестве криптографической функции. Для более безопасного создания случайных чисел криптографически используйте rand_s функции или , объявленные в стандартной библиотеке C++ в .

По умолчанию глобальное состояние этой функции ограничивается приложением. Чтобы изменить это поведение, см. статью Глобальное состояние в CRT.

Требования

Дополнительные сведения о совместимости см. в разделе Compatibility.

Пример

// crt_rand.c // This program seeds the random-number generator // with a fixed seed, then exercises the rand function // to demonstrate generating random numbers, and // random numbers in a specified range. #include // rand(), srand() #include // printf() void SimpleRandDemo(int n) < // Print n random numbers. for (int i = 0; i < n; i++) < printf(" %6d\n", rand()); >> void RangedRandDemo(int range_min, int range_max, int n) < // Generate random numbers in the interval [range_min, range_max], inclusive. for (int i = 0; i < n; i++) < // Note: This method of generating random numbers in a range isn't suitable for // applications that require high quality random numbers. // rand() has a small output range [0,32767], making it unsuitable for // generating random numbers across a large range using the method below. // The approach below also may result in a non-uniform distribution. // More robust random number functionality is available in the C++ header. // See https://learn.microsoft.com/cpp/standard-library/random int r = ((double)rand() / RAND_MAX) * (range_max - range_min) + range_min; printf(" %6d\n", r); > > int main(void) < // Seed the random-number generator with a fixed seed so that // the numbers will be the same every time we run. srand(1792); printf("Simple random number demo ====\n\n"); SimpleRandDemo(10); printf("\nRandom number in a range demo ====\n\n"); RangedRandDemo(-100, 100, 100000); >``` ```Output Simple random number demo ==== 5890 1279 19497 1207 11420 3377 15317 29489 9716 23323 Random number in a range demo ==== -82 -46 50 77 -47 32 76 -13 -58 90 

Источник

Оцените статью