* remove "\r" nonsense
[mascara-docs.git] / C / the.ansi.c.programming.language / notes.accompany.ansi.c / sx10n.html
blobb14939931ad2065e1c19a8f6b4de9f1f357f2fcf
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. -->
5 <html>
6 <head>
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>
12 </head>
13 <body>
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,
25 by default,
26 the sequence of pseudo-random numbers
27 returned by <TT>rand</TT>
28 is the same each time your program runs.
29 To randomize it,
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 &lt;stdlib.h&gt;
35 #include &lt;time.h&gt;
36 <br>
37 <br>
38 srand((unsigned int)time((time_t *)NULL));
39 </pre>which uses the <TT>time</TT> function mentioned on page 256 in
40 appendix B10.)
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)
44 with code like
45 <pre> rand() % 2
46 </pre>This looks like it ought to work,
47 but it turns out that
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
53 <TT>rand() % N</TT>
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.
58 </p><hr>
59 <p>
60 Read sequentially:
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>
64 </p>
65 <p>
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>
69 </p>
70 </body>
71 </html>