source: trunk/libs/newlib/src/newlib/libc/stdlib/rand.c @ 620

Last change on this file since 620 was 444, checked in by satin@…, 6 years ago

add newlib,libalmos-mkh, restructure shared_syscalls.h and mini-libc

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