SE450: Simulation: Random numbers [9/13] |
To get predictable numbers, use Random(long
seed)
. If you use the seed every time, you get the
same series of random numbers.
file:random/Util.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package random; import java.util.Random; public class Util { private Util() {} static private Random RANDOM = new Random(); /** doubles that differ by less than EPSILON should be considered equals */ static public final double EPSILON = 1e-9; static public boolean isEquals(double x, double y) { return Math.abs(x-y) <= EPSILON; } static public boolean isLessOrEquals(double x, double y) { return (x-y) <= EPSILON; } static public boolean isLess(double x, double y) { return (x-y) < -EPSILON; } static public void setRandomSeed(long seed) { RANDOM.setSeed(seed); } static public double nextRandom(double min, double max) { if (Util.isLess(max,min)) throw new IllegalArgumentException(max + " is smaller than " + min); return min + ((RANDOM.nextDouble()) * (max - min)); } }
file:random/UtilTEST.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package random; import static org.junit.Assert.*; import org.junit.Test; public class UtilTEST { @Test public void testEquals() { assertTrue (Util.isEquals(0.3, 0.3+0.5*Util.EPSILON)); assertFalse(Util.isEquals(0.3, 0.3+2.0*Util.EPSILON)); assertFalse(Util.isLess(0.3, 0.3+0.5*Util.EPSILON)); assertTrue (Util.isLess(0.3, 0.3+2.0*Util.EPSILON)); assertTrue (Util.isLessOrEquals(0.3, 0.3+0.5*Util.EPSILON)); assertTrue (Util.isLessOrEquals(0.3, 0.3+2.0*Util.EPSILON)); assertTrue (Util.isEquals(0.3+0.5*Util.EPSILON, 0.3)); assertFalse(Util.isEquals(0.3+2.0*Util.EPSILON, 0.3)); assertFalse(Util.isLess(0.3+0.5*Util.EPSILON, 0.3)); assertFalse(Util.isLess(0.3+2.0*Util.EPSILON, 0.3)); assertTrue (Util.isLessOrEquals(0.3+0.5*Util.EPSILON, 0.3)); assertFalse(Util.isLessOrEquals(0.3+2.0*Util.EPSILON, 0.3)); } @Test public void testRandom() { for (int i=0; i<100; i++) { double x=Util.nextRandom(i,i*i); assertTrue (Util.isLessOrEquals(i,x)); assertTrue (Util.isLessOrEquals(x,i*i)); } } }