Subversion Repositories Kolibri OS

Rev

Rev 4874 | Details | Compare with Previous | Last modification | View Log | RSS feed

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