ba9cc80f2b21da155697fa79fd4b3bbf33eb8a24
[newlib-cygwin.git] / newlib / libc / stdlib / rand.c
1 /*
2 FUNCTION
3 <<rand>>, <<srand>>---pseudo-random numbers
4
5 INDEX
6         rand
7 INDEX
8         srand
9 INDEX
10         rand_r
11
12 SYNOPSIS
13         #include <stdlib.h>
14         int rand(void);
15         void srand(unsigned int <[seed]>);
16         int rand_r(unsigned int *<[seed]>);
17
18 DESCRIPTION
19 <<rand>> returns a different integer each time it is called; each
20 integer is chosen by an algorithm designed to be unpredictable, so
21 that you can use <<rand>> when you require a random number.
22 The algorithm depends on a static variable called the ``random seed'';
23 starting with a given value of the random seed always produces the
24 same sequence of numbers in successive calls to <<rand>>.
25
26 You can set the random seed using <<srand>>; it does nothing beyond
27 storing its argument in the static variable used by <<rand>>.  You can
28 exploit this to make the pseudo-random sequence less predictable, if
29 you wish, by using some other unpredictable value (often the least
30 significant parts of a time-varying value) as the random seed before
31 beginning a sequence of calls to <<rand>>; or, if you wish to ensure
32 (for example, while debugging) that successive runs of your program
33 use the same ``random'' numbers, you can use <<srand>> to set the same
34 random seed at the outset.
35
36 RETURNS
37 <<rand>> returns the next pseudo-random integer in sequence; it is a
38 number between <<0>> and <<RAND_MAX>> (inclusive).
39
40 <<srand>> does not return a result.
41
42 NOTES
43 <<rand>> and <<srand>> are unsafe for multi-threaded applications.
44 <<rand_r>> is thread-safe and should be used instead.
45
46
47 PORTABILITY
48 <<rand>> is required by ANSI, but the algorithm for pseudo-random
49 number generation is not specified; therefore, even if you use
50 the same random seed, you cannot expect the same sequence of results
51 on two different systems.
52
53 <<rand>> requires no supporting OS subroutines.
54 */
55
56 #ifndef _REENT_ONLY
57
58 #include <stdlib.h>
59 #include <reent.h>
60
61 #ifdef _REENT_THREAD_LOCAL
62 _Thread_local unsigned long long _tls_rand_next = 1;
63 #endif
64
65 void
66 srand (unsigned int seed)
67 {
68   struct _reent *reent = _REENT;
69
70   _REENT_CHECK_RAND48(reent);
71   _REENT_RAND_NEXT(reent) = seed;
72 }
73
74 int
75 rand (void)
76 {
77   struct _reent *reent = _REENT;
78
79   /* This multiplier was obtained from Knuth, D.E., "The Art of
80      Computer Programming," Vol 2, Seminumerical Algorithms, Third
81      Edition, Addison-Wesley, 1998, p. 106 (line 26) & p. 108 */
82   _REENT_CHECK_RAND48(reent);
83   _REENT_RAND_NEXT(reent) =
84      _REENT_RAND_NEXT(reent) * __extension__ 6364136223846793005LL + 1;
85   return (int)((_REENT_RAND_NEXT(reent) >> 32) & RAND_MAX);
86 }
87
88 #endif /* _REENT_ONLY */
This page took 0.02594 seconds and 5 git commands to generate.