1 16 package org.apache.commons.math.random; 17 18 32 public abstract class AbstractRandomGenerator implements RandomGenerator { 33 34 41 private double cachedNormalDeviate = Double.NaN; 42 43 46 public AbstractRandomGenerator() { 47 super(); 48 49 } 50 51 57 public void clear() { 58 cachedNormalDeviate = Double.NaN; 59 } 60 61 72 public abstract void setSeed(long seed); 73 74 85 public void nextBytes(byte[] bytes) { 86 int bytesOut = 0; 87 while (bytesOut < bytes.length) { 88 int randInt = nextInt(); 89 for (int i = 0; i < 3; i++) { 90 if ( i > 0) { 91 randInt = randInt >> 8; 92 } 93 bytes[bytesOut++] = (byte) randInt; 94 if (bytesOut == bytes.length) { 95 return; 96 } 97 } 98 } 99 } 100 101 115 public int nextInt() { 116 return (int) (nextDouble() * Integer.MAX_VALUE); 117 } 118 119 135 public int nextInt(int n) { 136 if (n <= 0 ) { 137 throw new IllegalArgumentException ("upper bound must be positive"); 138 } 139 int result = (int) (nextDouble() * n); 140 return result < n ? result : n - 1; 141 } 142 143 157 public long nextLong() { 158 return (long) (nextDouble() * Long.MAX_VALUE); 159 } 160 161 175 public boolean nextBoolean() { 176 return nextDouble() <= 0.5; 177 } 178 179 193 public float nextFloat() { 194 return (float) nextDouble(); 195 } 196 197 209 public abstract double nextDouble(); 210 211 231 public double nextGaussian() { 232 if (!Double.isNaN(cachedNormalDeviate)) { 233 double dev = cachedNormalDeviate; 234 cachedNormalDeviate = Double.NaN; 235 return dev; 236 } 237 double v1 = 0; 238 double v2 = 0; 239 double s = 1; 240 while (s >=1 ) { 241 v1 = 2 * nextDouble() - 1; 242 v2 = 2 * nextDouble() - 1; 243 s = v1 * v1 + v2 * v2; 244 } 245 if (s != 0) { 246 s = Math.sqrt(-2 * Math.log(s) / s); 247 } 248 cachedNormalDeviate = v2 * s; 249 return v1 * s; 250 } 251 } 252 | Popular Tags |