Java Reference
In-Depth Information
1 package weiss.util;
2
3 /**
4 * Random number class, using a 48-bit
5 * linear congruential generator.
6 * @author Mark Allen Weiss
7 */
8 public class Random48
9 {
10 private static final long A = 25214903917L;
11 private static final long B = 48;
12 private static final long C = 11;
13 private static final long M = (1L<<B);
14 private static final long MASK = M-1;
15
16 public Random48( )
17 { this( System.nanoTime( ) ); }
18
19 public Random48( long initialValue )
20 { state = initialValue & MASK; }
21
22 public int nextInt( )
23 { return next( 32 ); }
24
25 public int nextInt( int N )
26 { return (int) ( Math.abs( nextLong( ) ) % N ); }
27
28 public double nextDouble( )
29 { return ( ( (long) ( next( 26 ) ) << 27 ) + next( 27 ) ) / (double)( 1L << 53 ); }
30
31 public long nextLong( )
32
{ return ( (long) ( next( 32 ) ) << 32 ) + next( 32 ); }
33
34 /**
35 * Return specified number of random bits
36 * @param bits number of bits to return
37 * @return specified random bits
38 * @throws IllegalArgumentException if bits is more than 32
39 */
40 private int next( int bits )
41 {
42 if( bits <= 0 || bits > 32 )
43 throw new IllegalArgumentException( );
44
45 state = ( A * state + C ) & MASK;
46
47 return (int) ( state >>> ( B - bits ) );
48 }
49
50 private long state;
51 }
figure 9.3
48-Bit Random Number Generator
Search WWH ::




Custom Search