1 <!DOCTYPE HTML PUBLIC
"-//W3O//DTD W3 HTML 2.0//EN">
2 <!-- This collection of hypertext pages is Copyright 1995, 1996 by Steve Summit. -->
3 <!-- This material may be freely redistributed and used -->
4 <!-- but may not be republished or sold without permission. -->
7 <link rev=
"owner" href=
"mailto:scs@eskimo.com">
8 <link rev=
"made" href=
"mailto:scs@eskimo.com">
9 <title>section
7.8.7: Random Number Generation
</title>
10 <link href=
"sx10m.html" rev=precedes
>
11 <link href=
"sx10.html" rev=subdocument
>
14 <H2>section
7.8.7: Random Number Generation
</H2>
16 <p>There is a typo in some printings;
17 the code for returning a floating-point random number in the
18 interval [
0,
1) should be
19 <pre> #define frand() ((double) rand() / (RAND_MAX+
1.0))
20 </pre></p><p>If you want to get random integers from M to N,
21 you can use something like
22 <pre> M + (int)(frand() * (N-M+
1))
23 </pre><pre></pre></p><p>``[Setting] the seed for
<TT>rand
</TT>''
24 refers to the fact that,
26 the sequence of pseudo-random numbers
27 returned by
<TT>rand
</TT>
28 is the same each time your program runs.
30 you can call
<TT>srand
</TT> at the beginning of the program,
31 handing it some truly random number,
32 such as a value having to do with the time of day.
33 (One way is with code like
34 <pre> #include
<stdlib.h
>
35 #include
<time.h
>
38 srand((unsigned int)time((time_t *)NULL));
39 </pre>which uses the
<TT>time
</TT> function mentioned on page
256 in
41 </p><p>One other caveat about
<TT>rand
</TT>:
42 don't try to generate random
0/
1 values
43 (to simulate a coin flip, perhaps)
46 </pre>This looks like it ought to work,
48 on some systems
<TT>rand
</TT> isn't always perfectly random,
49 and returns values which consistently alternate
50 even, odd, even, odd, etc.
51 (In fact, for similar reasons,
52 you shouldn't usually use
54 for any value of
<TT>N
</TT>.)
55 A good way to get random
0/
1 values would be
56 <pre> (int)(frand() *
2)
57 </pre>based on the other
<TT>frand()
</TT> examples above.
61 <a href=
"sx10m.html" rev=precedes
>prev
</a>
62 <a href=
"sx10.html" rev=subdocument
>up
</a>
63 <a href=
"top.html">top
</a>
66 This page by
<a href=
"http://www.eskimo.com/~scs/">Steve Summit
</a>
67 //
<a href=
"copyright.html">Copyright
</a> 1995,
1996
68 //
<a href=
"mailto:scs@eskimo.com">mail feedback
</a>