source: trunk/libs/newlib/src/newlib/libc/stdlib/random.c @ 444

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

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

File size: 2.3 KB
Line 
1/*
2FUNCTION
3<<random>>, <<srandom>>---pseudo-random numbers
4
5INDEX
6        random
7INDEX
8        srandom
9
10SYNOPSIS
11        #define _XOPEN_SOURCE 500
12        #include <stdlib.h>
13        long int random(void);
14        void srandom(unsigned int <[seed]>);
15
16
17
18DESCRIPTION
19<<random>> 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 <<random>> 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 <<random>>.
25
26You can set the random seed using <<srandom>>; 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 <<srandom>> to set the same
34random seed at the outset.
35
36RETURNS
37<<random>> returns the next pseudo-random integer in sequence; it is a
38number between <<0>> and <<RAND_MAX>> (inclusive).
39
40<<srandom>> does not return a result.
41
42NOTES
43<<random>> and <<srandom>> are unsafe for multi-threaded applications.
44
45_XOPEN_SOURCE may be any value >= 500.
46
47PORTABILITY
48<<random>> is required by XSI. This implementation uses the same
49algorithm as <<rand>>.
50
51<<random>> requires no supporting OS subroutines.
52*/
53
54#ifndef _REENT_ONLY
55
56#include <stdlib.h>
57#include <reent.h>
58
59void
60srandom (unsigned int seed)
61{
62  struct _reent *reent = _REENT;
63
64  _REENT_CHECK_RAND48(reent);
65  _REENT_RAND_NEXT(reent) = seed;
66}
67
68long int
69random (void)
70{
71  struct _reent *reent = _REENT;
72
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);
80}
81
82#endif /* _REENT_ONLY */
Note: See TracBrowser for help on using the repository browser.