Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To some extent, random number generators are horses for courses. The Random class implements an LCG with reasonably chosen parameters. But it still exhibits the following features:</p> <ul> <li>fairly short period (2^48)</li> <li>bits are not equally random (see my article on <a href="http://www.javamex.com/tutorials/random_numbers/lcg_bit_positions.shtml" rel="noreferrer">randomness of bit positions</a>)</li> <li>will only generate a small fraction of <em>combinations</em> of values (the famous problem of "<a href="http://www.javamex.com/tutorials/random_numbers/lcg_planes.shtml" rel="noreferrer">falling in the planes</a>")</li> </ul> <p>If these things don't matter to you, then Random has the redeeming feature of being provided as part of the JDK. It's good enough for things like casual games (but not ones where money is involved). There are no weak seeds as such.</p> <p>Another alternative which is the <a href="http://www.javamex.com/tutorials/random_numbers/xorshift.shtml" rel="noreferrer">XORShift generator</a>, which can be implemented in Java as follows:</p> <pre><code>public long randomLong() { x ^= (x &lt;&lt; 21); x ^= (x &gt;&gt;&gt; 35); x ^= (x &lt;&lt; 4); return x; } </code></pre> <p>For some very cheap operations, this has a period of 2^64-1 (zero is not permitted), and is simple enough to be inlined when you're generating values repeatedly. Various shift values are possible: see George Marsaglia's paper on XORShift Generators for more details. You can consider bits in the numbers generated as being equally random. One main weakness is that occasionally it will get into a "rut" where not many bits are set in the number, and then it takes a few generations to get out of this rut.</p> <p>Other possibilities are:</p> <ul> <li>combine different generators (e.g. feed the output from an XORShift generator into an LCG, then add the result to the output of an XORShift generator with different parameters): this generally allows the weaknesses of the different methods to be "smoothed out", and can give a longer period if the periods of the combined generators are carefully chosen</li> <li>add a "lag" (to give a longer period): essentially, where a generator would normally transform the last number generated, store a "history buffer" and transform, say, the (n-1023)th.</li> </ul> <p>I would say avoid generators that use a stupid amount of memory to give you a period longer than you really need (some have a period greater than the number of atoms in the universe-- you really don't usually need that). And note that "long period" doesn't necessarily mean "high quality generator" (though 2^48 is still a little bit low!).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload