Java Reference
In-Depth Information
1
private static final int A = 48271;
2
private static final int M = 2147483647;
3
private static final int Q = M / A;
4
private static final int R = M % A;
5
6
/**
7
* Construct this Random object with
8
* initial state obtained from system clock.
9
*/
10
public Random( )
11
{
12
this( (int) ( System.nanoTime( ) % Integer.MAX_VALUE ) );
13
}
14
15
/**
16
* Construct this Random object with
17
* specified initial state
18
* @param initialValue the initial state.
19
*/
20
public Random( int initialValue )
21
{
22
if( initialValue < 0 )
23
{
24
initialValue += M;
25
initialValue++;
26
}
27
28
state = initialValue;
29
if( state <= 0 )
30
state = 1;
31
}
32
33
/**
34
* Return a pseudorandom int, and change the
35
* internal state.
36
* @return the pseudorandom int.
37
*/
38
public int nextInt( )
39
{
40
int tmpState = A * ( state % Q ) - R * ( state / Q );
41
if( tmpState >= 0 )
42
state = tmpState;
43
else
44
state = tmpState + M;
45
46
return state;
47
}
figure 9.2
Random number generator that works if
INT_MAX
is at least
2
31
-1
Search WWH ::
Custom Search