From 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 Mon Sep 17 00:00:00 2001 From: Craig Jennings Date: Sun, 7 Apr 2024 13:41:34 -0500 Subject: new repository --- devdocs/c/numeric%2Frandom%2Frand.html | 46 ++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 devdocs/c/numeric%2Frandom%2Frand.html (limited to 'devdocs/c/numeric%2Frandom%2Frand.html') diff --git a/devdocs/c/numeric%2Frandom%2Frand.html b/devdocs/c/numeric%2Frandom%2Frand.html new file mode 100644 index 00000000..cd6aaf4c --- /dev/null +++ b/devdocs/c/numeric%2Frandom%2Frand.html @@ -0,0 +1,46 @@ +

rand

Defined in header <stdlib.h>
int rand();
+

Returns a pseudo-random integer value between ​0​ and RAND_MAX (0 and RAND_MAX included).

+

srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). Each time rand() is seeded with srand(), it must produce the same sequence of values.

+

rand() is not guaranteed to be thread-safe.

+

Parameters

(none)

+

Return value

Pseudo-random integer value between ​0​ and RAND_MAX, inclusive.

+

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, like cryptography.

+

POSIX requires that the period of the pseudo-random number generator used by rand be at least 232.

+

POSIX offered a thread-safe version of rand called rand_r, which is obsolete in favor of the drand48 family of functions.

+

Example

#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+ 
+int main(void)
+{
+    srand(time(NULL)); // use current time as seed for random generator
+    int random_variable = rand();
+    printf("Random value on [0,%d]: %d\n", RAND_MAX, random_variable);
+ 
+    // roll a 6-sided die 20 times
+    for (int n=0; n != 20; ++n) {
+        int x = 7;
+        while(x > 6) 
+            x = 1 + rand()/((RAND_MAX + 1u)/6); // Note: 1+rand()%6 is biased
+        printf("%d ",  x); 
+    }
+}

Possible output:

+
Random value on [0,2147483647]: 448749574
+3 1 3 1 4 2 2 1 3 6 4 4 3 1 6 2 3 2 6 1

References

See also

+ + +
seeds pseudo-random number generator
(function)
maximum possible value generated by rand()
(macro constant)
C++ documentation for rand
+

+ © cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
+ https://en.cppreference.com/w/c/numeric/random/rand +

+
-- cgit v1.2.3