/** * This generates a coin flip with a probability <tt>probability</tt> of returning true, else returning false. * <tt>probability</tt> must be between 0.0 and 1.0, inclusive. */ public boolean nextBoolean(final double probability) { if (probability < 0.0 || probability > 1.0) throw new IllegalArgumentException("probability must be between 0.0 and 1.0 inclusive."); if (probability == 0.0) return false; // fix half-open issues else if (probability == 1.0) return true; // fix half-open issues return nextDouble() < probability; }
/** * A bug fix for all JDK code including 1.2. nextGaussian can theoretically ask for the log of 0 and divide it by 0! See Java bug: * http://developer.java.sun.com/developer/bugParade/bugs/4254501.html. */ synchronized public double nextGaussian() { if (__haveNextNextGaussian) { __haveNextNextGaussian = false; return __nextNextGaussian; } else { double v1, v2, s; do { v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0 v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0 s = v1 * v1 + v2 * v2; } while (s >= 1 || s == 0); double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s) / s); __nextNextGaussian = v2 * multiplier; __haveNextNextGaussian = true; return v1 * multiplier; } }
/** * Returns a double in the range from 0.0 to 1.0, possibly inclusive of 0.0 and 1.0 themselves. Thus: * * Expression * Interval * nextDouble(false, false) * (0.0, 1.0) * nextDouble(true, false) * [0.0, 1.0) * nextDouble(false, true) * (0.0, 1.0] * nextDouble(true, true) * [0.0, 1.0] * * * This version preserves all possible random values in the double range. */ public double nextDouble(boolean includeZero, boolean includeOne) { double d = 0.0; do { d = nextDouble(); // grab a value, initially from half-open [0.0, 1.0) if (includeOne && nextBoolean()) d += 1.0; // if includeOne, with 1/2 probability, push to [1.0, 2.0) } while ((d > 1.0) || // everything above 1.0 is always invalid (!includeZero && d == 0.0)); // if we're not including zero, 0.0 is invalid return d; }
r = new MersenneTwister(SEED); for (j = 0; j < 1000; j++) { System.out.print(r.nextDouble() + " "); if (j % 3 == 2) System.out.println();