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, and including it's lower bound up to, but not including it's upper bound [lower, upper), but they don't answer my question as they do not address this case.
I've come up with two "solutions" to the problem, but am not really satisfied by either.
First "solution"
double myvalue;
do { myvalue = myrandom.nextDouble() * (upper - lower) + lower; } while (myvalue != lower);
While this will almost anytime instantly give a result it seems inconsistent and clunky, and on the off-chance that the rng returns 0.0 a lot, it's inefficient aswell.
Second "solution"
double myvalue =
0.5 * (1.0 + myrandom.nextDouble() - myrandom.nextDouble()) * (upper - lower) + lower;
While this will guarantee me a valid number on the first try, I don't believe the distribution is uniform in this case.
Thanks
Aucun commentaire:
Enregistrer un commentaire