Cygwin: mmap: allow remapping part of an existing anonymous mapping
[newlib-cygwin.git] / newlib / libc / stdlib / random.c
blob131dc056c068c4f400725846d8ffb41c5fe00660
1 /*
2 FUNCTION
3 <<random>>, <<srandom>>---pseudo-random numbers
5 INDEX
6 random
7 INDEX
8 srandom
10 SYNOPSIS
11 #define _XOPEN_SOURCE 500
12 #include <stdlib.h>
13 long int random(void);
14 void srandom(unsigned int <[seed]>);
18 DESCRIPTION
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.
36 RETURNS
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.
42 NOTES
43 <<random>> and <<srandom>> are unsafe for multi-threaded applications.
45 _XOPEN_SOURCE may be any value >= 500.
47 PORTABILITY
48 <<random>> is required by XSI. This implementation uses the same
49 algorithm as <<rand>>.
51 <<random>> requires no supporting OS subroutines.
54 #ifndef _REENT_ONLY
56 #include <stdlib.h>
57 #include <reent.h>
59 void
60 srandom (unsigned int seed)
62 struct _reent *reent = _REENT;
64 _REENT_CHECK_RAND48(reent);
65 _REENT_RAND_NEXT(reent) = seed;
68 long int
69 random (void)
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 */