Random floating point double in Inclusive Range

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

    I believe there is much better decision but this one should work :)

    function randomInRange(min, max) {
      return Math.random() < 0.5 ? ((1-Math.random()) * (max-min) + min) : (Math.random() * (max-min) + min);
    }
    
    0 讨论(0)
  • 2020-12-01 18:37

    Given the "extremely large" number of values between 0 and 1, does it really matter? The chances of actually hitting 1 are tiny, so it's very unlikely to make a significant difference to anything you're doing.

    0 讨论(0)
  • 2020-12-01 18:38
    private static double random(double min, double max) {
        final double r = Math.random();
        return (r >= 0.5d ? 1.5d - r : r) * (max - min) + min;
    }
    
    0 讨论(0)
  • 2020-12-01 18:39

    I am fairly less experienced, So I am also looking for solutions as well.

    This is my rough thought:

    Random number generators produce numbers in [0,1) instead of [0,1],

    Because [0,1) is an unit length that can be followed by [1,2) and so on without overlapping.

    For random[x, y], You can do this:

    float randomInclusive(x, y){
    
        float MIN = smallest_value_above_zero;
        float result;
        do{
            result = random(x, (y + MIN));
        } while(result > y);
        return result;
    }
    

    Where all values in [x, y] has the same possibility to be picked, and you can reach y now.

    0 讨论(0)
  • 2020-12-01 18:40

    How about this?

    function randomInRange(min, max){
        var n = Math.random() * (max - min + 0.1) + min;
        return n > max ? randomInRange(min, max) : n;
    }
    

    If you get stack overflow on this I'll buy you a present.

    -- EDIT: never mind about the present. I got wild with:

    randomInRange(0, 0.0000000000000000001)
    

    and got stack overflow.

    0 讨论(0)
  • 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.

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