vendredi 26 juillet 2019

How much is excluded from the bound when generating pseudo-random doubles with nextDouble()?

I have looked at the SplittableRandom class' nextDouble() info on JavaDocs, but it doesn't tell me how close the return value of the nextDouble(double bound) method can get to the "bound" argument. I don't know if I can get a full range of values between 0.0 and 100.0 inclusive by typing foo.nextDouble(100.0 + Double.MIN_VALUE).

How can I pseudo-randomly return a number from 0.0 to 100.0 using the nextDouble(double bound) method?

/**
 * Returns a getRandom element from this.values.
 * Elements with higher associated percentage-change values (in this.keys)
 * are more likely to be returned.
 * <p>
 * Throws an IllegalArgumentException if this.sum is not equal to 100.
 */
public T getElement() {

   SplittableRandom random = new SplittableRandom();

   if(sum != 100.0)
      throw new IllegalArgumentException("sum of chances must == 100.0");

   final double choice = random.nextDouble(100.0 + Double.MIN_VALUE);

   /* Iterate through this.keys until the sum of traversed elements is less than
    * or equal to the choice variable. Then return the this.value element at the
    * same index as the latest traversed element of this.keys.*/

   double percentageSum = 0.0;
   for (int i = 0; i < this.keys.size(); i++) {

      percentageSum += this.keys.get(i);

      if (choice <= percentageSum)
         return this.values.get(i);
   }

   throw new AssertionError("unreachable code reached");
}




Aucun commentaire:

Enregistrer un commentaire