    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Random Confusion</title>
        <link>https://members.accu.org/index.php/articles/2284</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + CVu Journal Vol 28, #4 - September 2016</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c365/">284</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-365/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+365/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Random Confusion</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 05 September 2016 16:35:15 +01:00 or Mon, 05 September 2016 16:35:15 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Silas S. Brown tries to clear up a muddle about Standard Câ€™s rand().</p>
<p><strong>Body:</strong>&nbsp;<p>The Standard C way of obtaining random numbers is to call <code>srand()</code> and <code>rand()</code>, defined in <span class="filename">stdlib.h</span>. Unfortunately, the manual pages of BSD state categorically that <code>rand()</code> is not very good, and a function called <code>random()</code> should be used in its place. This includes Mac OS X (which was derived from BSD), and it would appear that some poorly-written books have copied this advice without realising that <code>random()</code> is not actually Standard C. Searching the Web will show quite a few discussion pages where beginners have read books that told them to use <code>random()</code> instead of <code>rand()</code>, and others have told them this is not Standard C and the book is not very good, but they rarely note where the confusion came from. (I would chime in myself on those threads if it werenâ€™t so much hassle to sign up for an account on each one.)</p>

<p>So perhaps we should make a little public service announcement: <code>rand()</code> is Standard C; <code>random()</code> is Standard POSIX.</p>

<p>True, <code>random()</code>â€™s being in POSIX means itâ€™s available on all modern Unix systems including BSD, Mac OS X and GNU/Linux. But itâ€™s not there on Windows and the confusion is (for once) not Microsoftâ€™s fault. Itâ€™s also unlikely to be there on other platforms (PDAs and so on).</p>

<p>When the BSD manual says <code>rand()</code> is not very good, what it really means is, BSDâ€™s implementation of it is not very good. The C standard gives a sample implementation of <code>rand</code> but does not mandate that particular implementation. BSD (at least the version of it in Appleâ€™s source) essentially just multiplies the previous number by 16807 and leaves it at that. In the early 1980s, 4.2BSD (1983) and 4.3BSD (1986) introduced <code>random() </code>to be a â€˜better <code>rand</code>â€™, but they didnâ€™t upgrade the behaviour of their <code>rand()</code>, presumably because they didnâ€™t want to break any programs which relied on their old implementation-specific behaviour of this function.</p>

<p>The GNU/Linux C library (at least nowadays) does the sensible thing and makes <code>rand()</code> equal to <code>random()</code>, so you get the better behaviour no matter which one you call. In that case I suggest you call <code>rand()</code> because then youâ€™re writing Standard C. But their manual page suggests you prefer <code>random()</code> because then your code will work better on BSD.</p>

<p>The Windows implementation of <code>rand()</code> is better than BSDâ€™s: it multiplies by 214013, adds 2531011 and returns bits 30 to 16 of the result. Of course, thatâ€™s not good enough for cryptography (and you certainly shouldnâ€™t rely on the standard <code>rand()</code> being good enough for cryptography on any platform; if you want cryptographically-strong random numbers, make sure you can find out how to get them properly!), but it should be fine for most scientific or simulation purposes and you donâ€™t have to worry about disregarding the low-order bits (which is just as well, as there are only 15 bits to start with).</p>

<p>(Versions of WINE prior to 2006 just did <code>rand()</code> &amp; 0x7fff, but this was then replaced with an implementation of what MSVC actually does. So if youâ€™re on Unix and cross-compiling for Windows, you can run your program in WINE and get the same random sequence that it would get on Windows if seeded to the same value.)</p>

<p>So what to do about <code>random()</code>? A first thought might be â€˜use <code>rand()</code> on Windows, <code>random()</code> everywhere elseâ€™ but that wonâ€™t help with ports to non-Windows non-Unix systems (yes these do exist). Since GNU/Linux nowadays gives you good behaviour no matter which one you call, it would be better to say â€˜use <code>random()</code> on BSD, <code>rand()</code> everywhere elseâ€™. You can do that by checking for the <code>BSD</code> macro, which is defined in <span class="filename">sys/param.h</span> (a header file which is also available when cross-compiling for Windows) â€“ see Listing 1.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &lt;stdlib.h&gt;
#include &lt;sys/param.h&gt;
#ifdef BSD
/* avoid BSD's bad old rand() implementation */
#define rand random
#define srand srandom
#endif /* BSD */
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>If you want to make your programâ€™s behaviour 100% reproducible no matter which system it is compiled on, you had better provide your own random number generator, because you never know which one youâ€™re going to get from the standard library. Seeding it to the same value makes the sequence reproducible only on that particular implementation of the C library (and that particular version of it at that: most platforms are not as obsessive as BSD is about keeping their old behaviour from version to version). The code in Listing 2 should reproduce Microsoftâ€™s behaviour; Iâ€™m setting the functions to static so they wonâ€™t be visible outside the current C module, just in case some library function depends on the libraryâ€™s implementation of <code>rand()</code>. Feel free to use this in your code as it seems to be a public-domain method (at least I hope so; if Microsoft sues you for using two of their numbers, change them! but do check some good texts for alternatives, as youâ€™re less likely to end up with a good generator if you just pick them out of thin air yourself.)</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#ifdef RAND_MAX
#undef RAND_MAX
#endif
#define RAND_MAX 0x7FFF
static unsigned long seed = 1;
static void srand(unsigned int newSeed) {
   seed = newSeed;
}
static int rand() {
   seed = (seed*214013L) + 2531011L;
   return (seed &gt;&gt; 16) &amp; 0x7FFF;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>The XorShift generator discovered by George Marsaglia in 2003 gives generally better random numbers and is usually faster. It can be implemented thus:</p>

<pre class="programlisting">
  #include &lt;stdint.h&gt;
  int XS_rand() {
    static uint64_t s=1;
    s^=s&gt;&gt;12; s^=s&lt;&lt;25; s^=s&gt;&gt;27;
    return s &amp; 0x7FFFFFFF;
  }</pre>

<p>On x86 processors, bit shifts and XORs can be done in one cycle each, whereas multiplications can take 3 or 4 cycles depending on the processor (although pipelining and other types of instruction-level parallelism can hide that latency in some circumstances). Even additions can take multiple cycles on some CPUs. Thus Xorshift (which takes three XORs and three shifts) is almost certainly going to be at least as fast, and likely faster, than a common linear congruential generator which uses multiplication and addition.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
