Random floating point double in Inclusive Range

后端 未结 13 665
感动是毒
感动是毒 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:42

    Just pick your half-open interval slightly bigger, so that your chosen closed interval is a subset. Then, keep generating the random variable until it lands in said closed interval.

    Example: If you want something uniform in [3,8], then repeatedly regenerate a uniform random variable in [3,9) until it happens to land in [3,8].

    function randomInRangeInclusive(min,max) {
     var ret;
     for (;;) {
      ret = min + ( Math.random() * (max-min) * 1.1 );
      if ( ret <= max ) { break; }
     }
     return ret;
    }
    

    Note: The amount of times you generate the half-open R.V. is random and potentially infinite, but you can make the expected number of calls otherwise as close to 1 as you like, and I don't think there exists a solution that doesn't potentially call infinitely many times.

提交回复
热议问题