Random floating point double in Inclusive Range

后端 未结 13 676
感动是毒
感动是毒 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题