Random floating point double in Inclusive Range

后端 未结 13 689
感动是毒
感动是毒 2020-12-01 18:14

We can easily get random floating point numbers within a desired range [X,Y) (note that X is inclusive and Y is exclusive) with the function listed below since

13条回答
  •  臣服心动
    2020-12-01 18:28

    My solution to this problem has always been to use the following in place of your upper bound.

    Math.nextAfter(upperBound,upperBound+1)
    

    or

    upperBound + Double.MIN_VALUE
    

    So your code would look like this:

    double myRandomNum = Math.random() * Math.nextAfter(upperBound,upperBound+1) + lowerBound;
    

    or

    double myRandomNum = Math.random() * (upperBound + Double.MIN_VALUE) + lowerBound;
    

    This simply increments your upper bound by the smallest double (Double.MIN_VALUE) so that your upper bound will be included as a possibility in the random calculation.

    This is a good way to go about it because it does not skew the probabilities in favor of any one number.

    The only case this wouldn't work is where your upper bound is equal to Double.MAX_VALUE

提交回复
热议问题