Write a truly inclusive random method for javascript

前端 未结 9 1478
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 11:25

Javascript\'s MATH object has a random method that returns from the set [0,1) 0 inclusive, 1 exclusive. Is there a way to return a truly random method that includes 1.

9条回答
  •  情歌与酒
    2020-11-30 11:44

    The Math.random function returns a random number between 0 and 1, where 0 is inclusive and 1 is exclusive. This means that the only way to properly distribute the random numbers as integers in an interval is to use an exclusive upper limit.

    To specify an inclusive upper limit, you just add one to it to make it exclusive in the calculation. This will distribute the random numbers correctly between 7 and 12, inclusive:

    var min = 7;
    var max = 12;
    var rnd = min + Math.floor(Math.random() * (max - min + 1));
    

提交回复
热议问题