3 <<random>>, <<srandom>>---pseudo-random numbers
11 #define _XOPEN_SOURCE 500
13 long int random(void);
14 void srandom(unsigned int <[seed]>);
19 <<random>> 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 <<random>> 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 <<random>>.
26 You can set the random seed using <<srandom>>; 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 <<srandom>> to set the same
34 random seed at the outset.
37 <<random>> returns the next pseudo-random integer in sequence; it is a
38 number between <<0>> and <<RAND_MAX>> (inclusive).
40 <<srandom>> does not return a result.
43 <<random>> and <<srandom>> are unsafe for multi-threaded applications.
45 _XOPEN_SOURCE may be any value >= 500.
48 <<random>> is required by XSI. This implementation uses the same
49 algorithm as <<rand>>.
51 <<random>> requires no supporting OS subroutines.
60 srandom (unsigned int seed
)
62 struct _reent
*reent
= _REENT
;
64 _REENT_CHECK_RAND48(reent
);
65 _REENT_RAND_NEXT(reent
) = seed
;
71 struct _reent
*reent
= _REENT
;
73 /* This multiplier was obtained from Knuth, D.E., "The Art of
74 Computer Programming," Vol 2, Seminumerical Algorithms, Third
75 Edition, Addison-Wesley, 1998, p. 106 (line 26) & p. 108 */
76 _REENT_CHECK_RAND48(reent
);
77 _REENT_RAND_NEXT(reent
) =
78 _REENT_RAND_NEXT(reent
) * __extension__
6364136223846793005LL + 1;
79 return (long int)((_REENT_RAND_NEXT(reent
) >> 32) & RAND_MAX
);
82 #endif /* _REENT_ONLY */