/** * Returns a float in the range from 0.0f to 1.0f, possibly inclusive of 0.0f and 1.0f themselves. Thus: * * Expression Interval nextFloat(false, false) (0.0f, 1.0f) nextFloat(true, false) [0.0f, 1.0f) nextFloat(false, true) (0.0f, * 1.0f] nextFloat(true, true) [0.0f, 1.0f] This version preserves all possible random values in the float range. */ public double nextFloat(boolean includeZero, boolean includeOne) { float d = 0.0f; do { d = nextFloat(); // grab a value, initially from half-open [0.0f, 1.0f) if (includeOne && nextBoolean()) d += 1.0f; // if includeOne, with 1/2 probability, push to [1.0f, 2.0f) } while ((d > 1.0f) || // everything above 1.0f is always invalid (!includeZero && d == 0.0f)); // if we're not including zero, 0.0f is invalid return d; }
/** * 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; }