Generating a random double in an exclusive range

前端 未结 2 1669
既然无缘
既然无缘 2020-12-20 08:42

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

相关标签:
2条回答
  • 2020-12-20 09:13

    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 <=
    
    0 讨论(0)
  • 2020-12-20 09:16

    Try ThreadLocalRandom.current().nextDouble(origin + 1, bound). Per the javadoc, min is inclusive and max is exclusive by default

    0 讨论(0)
提交回复
热议问题