I\'m trying to generate a random double between but not including it\'s lower and upper bound (lower, upper). I\'ve seen a lot of questions about generating a number from, a
Your first code is quite correct.
double myvalue;
do {
myvalue = myrandom.nextDouble() * (upper - lower) + lower;
} while (myvalue == lower); // Replace != with ==
Simply replace !=
with ==
. It is not true that this is not efficient.
A look to efficiency of the code.
Taking a look on the code of nextDouble
you can see that it is calculated generating a random long value.
It means that basically you will have 1 possibility to repeat the loop over 2 * 9,223,372,036,854,775,807 (the range of long values minus 1).
Additional Note: because you are using double
and not a BigDecimal
you can obtain a myvalue
that is close to the lower
bound, but lower than it, so it is better to change the code to exclude also values lower than lower
. It doesn't change the efficiency of your code.
double myvalue;
do {
myvalue = myrandom.nextDouble() * (upper - lower) + lower;
} while (myvalue <= lower); // Replace != with <=
Try ThreadLocalRandom.current().nextDouble(origin + 1, bound)
. Per the javadoc, min is inclusive and max is exclusive by default