# Generating random whole numbers in JavaScript in a specific range?

ID : 350

viewed : 144

### Top 5 Answer for Generating random whole numbers in JavaScript in a specific range?

96

There are some examples on the Mozilla Developer Network page:

``/**  * Returns a random number between min (inclusive) and max (exclusive)  */ function getRandomArbitrary(min, max) {     return Math.random() * (max - min) + min; }  /**  * Returns a random integer between min (inclusive) and max (inclusive).  * The value is no lower than min (or the next integer greater than min  * if min isn't an integer) and no greater than max (or the next integer  * lower than max if max isn't an integer).  * Using Math.round() will give you a non-uniform distribution!  */ function getRandomInt(min, max) {     min = Math.ceil(min);     max = Math.floor(max);     return Math.floor(Math.random() * (max - min + 1)) + min; } ``

Here's the logic behind it. It's a simple rule of three:

`Math.random()` returns a `Number` between 0 (inclusive) and 1 (exclusive). So we have an interval like this:

``[0 .................................... 1) ``

Now, we'd like a number between `min` (inclusive) and `max` (exclusive):

``[0 .................................... 1) [min .................................. max) ``

We can use the `Math.random` to get the correspondent in the [min, max) interval. But, first we should factor a little bit the problem by subtracting `min` from the second interval:

``[0 .................................... 1) [min - min ............................ max - min) ``

This gives:

``[0 .................................... 1) [0 .................................... max - min) ``

We may now apply `Math.random` and then calculate the correspondent. Let's choose a random number:

``                Math.random()                     | [0 .................................... 1) [0 .................................... max - min)                     |                     x (what we need) ``

So, in order to find `x`, we would do:

``x = Math.random() * (max - min); ``

Don't forget to add `min` back, so that we get a number in the [min, max) interval:

``x = Math.random() * (max - min) + min; ``

That was the first function from MDN. The second one, returns an integer between `min` and `max`, both inclusive.

Now for getting integers, you could use `round`, `ceil` or `floor`.

You could use `Math.round(Math.random() * (max - min)) + min`, this however gives a non-even distribution. Both, `min` and `max` only have approximately half the chance to roll:

``min...min+0.5...min+1...min+1.5   ...    max-0.5....max └───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘   ← Math.round()    min          min+1                          max ``

With `max` excluded from the interval, it has an even less chance to roll than `min`.

With `Math.floor(Math.random() * (max - min +1)) + min` you have a perfectly even distribution.

``min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval) |        |        |         |        |        | └───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘   ← Math.floor()    min     min+1               max-1    max ``

You can't use `ceil()` and `-1` in that equation because `max` now had a slightly less chance to roll, but you can roll the (unwanted) `min-1` result too.

84

``var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; ``

70

# Math.random()

Returns an integer random number between min (included) and max (included):

``function randomInteger(min, max) {   return Math.floor(Math.random() * (max - min + 1)) + min; } ``

Or any random number between min (included) and max (not included):

``function randomNumber(min, max) {   return Math.random() * (max - min) + min; } ``

Useful examples (integers):

``// 0 -> 10 Math.floor(Math.random() * 11);  // 1 -> 10 Math.floor(Math.random() * 10) + 1;  // 5 -> 20 Math.floor(Math.random() * 16) + 5;  // -10 -> (-2) Math.floor(Math.random() * 9) - 10; ``

** And always nice to be reminded (Mozilla):

Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

61

``function getRandomizer(bottom, top) {     return function() {         return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;     } } ``

usage:

``var rollDie = getRandomizer( 1, 6 );  var results = "" for ( var i = 0; i<1000; i++ ) {     results += rollDie() + " ";    //make a string filled with 1000 random numbers in the range 1-6. } ``

breakdown:

We are returning a function (borrowing from functional programming) that when called, will return a random integer between the the values `bottom` and `top`, inclusive. We say 'inclusive' because we want to include both bottom and top in the range of numbers that can be returned. This way, `getRandomizer( 1, 6 )` will return either 1, 2, 3, 4, 5, or 6.

(bottom is lower number, top is greater number)

``Math.random() * ( 1 + top - bottom ) ``

`Math.random()` returns a random double between 0 and 1, and if we multiply it by one plus the difference between `top` and `bottom`, we'll get a double somewhere between `0` and `1+b-a`.

``Math.floor( Math.random() * ( 1 + top - bottom ) ) ``

`Math.floor` rounds the number down to the nearest integer. So we now have all the integers between `0` and `top-bottom`. The 1 looks confusing, but it needs to be there because we are always rounding down, so the top number will never actually be reached without it. The random decimal we generate needs to be in the range `0` to `(1+top-bottom)` so we can round down and get an int in the range `0` to `top-bottom`

``Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom ``

The code in the previous example gave us an integer in the range `0` and `top-bottom`, so all we need to do now is add `bottom` to that result to get an integer in the range `bottom` and `top` inclusive. :D

NOTE: If you pass in a non-integer value or the greater number first you'll get undesirable behavior, but unless anyone requests it I am not going to delve into the argument checking code as its rather far from the intent of the original question.

58

Return a random number between 1 and 10:

``Math.floor((Math.random()*10) + 1);  ``

Return a random number between 1 and 100:

``Math.floor((Math.random()*100) + 1) ``