1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.hipparchus.random;
24
25 import org.hipparchus.exception.LocalizedCoreFormats;
26 import org.hipparchus.exception.MathIllegalArgumentException;
27 import org.hipparchus.util.FastMath;
28 import org.hipparchus.util.SinCos;
29
30
31
32
33 abstract class BaseRandomGenerator implements RandomGenerator {
34
35
36 private double nextGaussian = Double.NaN;
37
38
39 @Override
40 public void setSeed(int seed) {
41 setSeed(new int[] { seed });
42 }
43
44
45 @Override
46 public void setSeed(long seed) {
47 setSeed(new int[] { (int) (seed >>> 32), (int) (seed & 0xffffffffL) });
48 }
49
50
51 @Override
52 public int nextInt(int n) throws IllegalArgumentException {
53 if (n <= 0) {
54 throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_SMALL_BOUND_EXCLUDED,
55 n, 0);
56 }
57
58 if ((n & -n) == n) {
59 return (int) ((n * (long) (nextInt() >>> 1)) >> 31);
60 }
61 int bits;
62 int val;
63 do {
64 bits = nextInt() >>> 1;
65 val = bits % n;
66 } while (bits - val + (n - 1) < 0);
67 return val;
68 }
69
70
71 @Override
72 public long nextLong(long n) {
73 if (n <= 0) {
74 throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_SMALL_BOUND_EXCLUDED,
75 n, 0);
76 }
77
78 long bits;
79 long val;
80 do {
81 bits = nextLong() >>> 1;
82 val = bits % n;
83 } while (bits - val + (n - 1) < 0);
84 return val;
85 }
86
87
88 @Override
89 public double nextGaussian() {
90
91 final double random;
92 if (Double.isNaN(nextGaussian)) {
93
94 final double x = nextDouble();
95 final double y = nextDouble();
96 final double alpha = 2 * FastMath.PI * x;
97 final double r = FastMath.sqrt(-2 * FastMath.log(y));
98 final SinCos scAlpha = FastMath.sinCos(alpha);
99 random = r * scAlpha.cos();
100 nextGaussian = r * scAlpha.sin();
101 } else {
102
103 random = nextGaussian;
104 nextGaussian = Double.NaN;
105 }
106
107 return random;
108
109 }
110
111
112
113
114
115 protected void clearCache() {
116 nextGaussian = Double.NaN;
117 }
118
119
120 @Override
121 public String toString() {
122 return getClass().getName();
123 }
124
125 }