Note that there are some explanatory texts on larger screens.

plurals
  1. POPort of Random generator from C to Java?
    text
    copied!<p>George Marsaglia has written an excellent random number generator that is extremely fast, simple, and has a much higher period than the Mersenne Twister. Here is the code with a description:</p> <p><a href="http://school.anhb.uwa.edu.au/personalpages/kwessen/shared/Marsaglia03.html" rel="noreferrer">good C random number generator</a></p> <p>I wanted to port the CMWC4096 code to Java, but it uses several unsigned datatypes so I am not sure how to do this properly. Here is the full C code:</p> <pre><code>/* choose random initial c&lt;809430660 and */ /* 4096 random 32-bit integers for Q[] */ static unsigned long Q[4096],c=362436; unsigned long CMWC4096(void) { unsigned long long t, a=18782LL; static unsigned long i=4095; unsigned long x,r=0xfffffffe; i = (i+1) &amp; 4095; t = a*Q[i] + c; c = (t&gt;&gt;32); x = t + c; if (x &lt; c) { x++; c++; } return (Q[i] = r - x); } </code></pre> <p>Can anyone port this to Java? How does this work when you only have signed numbers available?</p> <p><strong>EDIT:</strong> Thanks everybody for the quick answers! For the first 100 million numbers this java code seems to produce the same result as the C code. It is 3 times faster than Java's java.util.Random.</p> <pre><code>public class ComplimentaryMultiplyWithCarryRandom { /** * Choose 4096 random 32-bit integers */ private long[] Q; /** * choose random initial c&lt;809430660 */ private long c = 362436; private int i; public ComplimentaryMultiplyWithCarryRandom() { Random r = new Random(1); Q = new long[4096]; // TODO initialize with real random 32bit values for (int i = 0; i &lt; 4096; ++i) { long v = r.nextInt(); v -= Integer.MIN_VALUE; Q[i] = v; } i = 4095; } int next() { i = (i + 1) &amp; 4095; long t = 18782 * Q[i] + c; c = t &gt;&gt;&gt; 32; long x = (t + c) &amp; 0xffffffffL; if (x &lt; c) { ++x; ++c; } long v = 0xfffffffeL - x; Q[i] = v; return (int) v; } } </code></pre>
 

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