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...    ...      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.

Answer from IonuΘ› G. Stan on Stack Overflow
🌐
freeCodeCamp
forum.freecodecamp.org β€Ί guide
freeCodeCamp Challenge Guide: Generate Random Whole Numbers within a Range - Guide - The freeCodeCamp Forum
October 16, 2019 - Generate Random Whole Numbers within a Range Hints Hint 1 randomRange should use both myMax and myMin, and return a random number in your range. You cannot pass the test if you are only re-using the function ourRandomR…
Top answer
1 of 16
4922

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...    ...      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.

2 of 16
657
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
🌐
freeCodeCamp
freecodecamp.org β€Ί news β€Ί generate-random-whole-numbers-within-a-range-javascript
How to Generate Random Whole Numbers within a Range using JavaScript Math.floor - Solved
November 28, 2019 - Quick Solution function randomRange(myMin, myMax) { return Math.floor(Math.random() * (myMax - myMin + 1) + myMin); } Code Explanation Math.random() generates our random number between 0 and β‰ˆ 0.9. Before multiplying it, it resolves the part ...
🌐
freeCodeCamp
forum.freecodecamp.org β€Ί javascript
Generate Random Whole Numbers within a Range-- Is this how range works?
October 14, 2018 - Tell us what’s happening: Why is range like this: (myMax - myMin + 1)) + myMin; We’re subtraction myMax from myMin then adding 1, then adding myMin again? Huh? Is that how range is supposed to be formatted? I don’t get it. Your code so far // Example function ourRandomRange(ourMin, ourMax) { return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin; } ourRandomRange(1, 9); // Only change code below this line. function randomRange(myMin, myMax) { return Math.floor(Math.rando...
🌐
DataCamp
datacamp.com β€Ί tutorial β€Ί excel-random-number-generator
Excel Random Number Generator: 3 Different Methods | DataCamp
February 18, 2025 - Excel can generate random numbers as single decimals, whole numbers within a range, or even entire tables of values.
🌐
Reddit
reddit.com β€Ί r/learnjavascript β€Ί generate random whole numbers within a range. no quite understanding. need help.
r/learnjavascript on Reddit: Generate Random Whole Numbers within a Range. No quite understanding. Need help.
September 15, 2018 -

Hello! So i understand how Math.random() and Math.floor() works. It returns a random decimal number between 0 and 1. If you multiply it by a number you get a random number between 0 and the number you multiply by. Then Math.floor just rounds it down to the to an integer. Example: Math.random() * 10 = 0.42 * 10 = 4,2 = 4

Here is a function that returns a random number between a specified range (ourMin and ourMax):

function ourRandomRange(ourMin, ourMax) {
  return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}

console.log(ourRandomRange(5, 10));

I just can't seem to understand the logic in this function. If there is a kind patient soul out there that can explain it to me in simple steps it would be much appreciated!

Top answer
1 of 2
12
let randomValue = Math.random(); // Let's assume random value gets set to 0.234, but I want an integer between 1 and 10; let integerValue = 10 * randomValue; // integerValue is 2.34, which isn't an actual integer. So we fix that with Math.floor(); integerValue = Math.floor(integerValue); /* A nuanced thing about Math.random is that it will return the range 0-1, but one is not inclusive. This means the actual range is 0 - 0.99999999999999999~. Which also means if I want a numebr between 1 and 10, I can never get 10 with Math.floor(). Since 10 * 0.999999999999999 is 9.999999, and Math.floor() makes this 9. How do we fix this? */ integerValue = integerValue + 1; // Finally we can put all this logic into a single line. let randomNumber = Math.floor(Math.random() * 10) + 1; //******************************************************************** // Now lets talk about the doing this with a range like 5-10, first we need a random value. let randomValue = Math.random(); /* Since we want a range between 5-10, we need to figure out how big the range actually is. This is pretty simple to figure out just take the max(10) value and subtract the min(5) value. */ let randomRangeSize = 10 - 5; // Now we can use the same logic as before to get a random number that is within the size of the range. let randomNumber = Math.floor(Math.random() * randomRangeSize) + 1; /* So random number is now between 1 - 5, but our range is actually 5-10, so what do we do? Just add the min value of the range to the result. */ randomNumber = randomNumber + 5; // So we can make a simple function to do this for us. function randomRange(minValue, maxValue) { let randomRangeSize = maxValue - minValue; let randomNumber = Math.floor(Math.random() * randomRangeSize); randomNumber = randomNumber + minValue; return randomNumber; } console.log(randomRange(5, 10)); /* You may have noticed that technically this logic will only produce the values 5-9. This has to do whether the values in a range are inclusive or exclusive. If you want the possible random values to be 5,6,7,8,9,10 you need to calculate the range size differently. Because the actual number of values is 6 instead of 5(10-5). Which is simple enough. */ function randomRange(minValue, maxValue) { //Just add a +1 here to get the range fixed. let randomRangeSize = (maxValue - minValue) + 1; let randomNumber = Math.floor(Math.random() * randomRangeSize); randomNumber = randomNumber + minValue; return randomNumber; } console.log(randomRange(5, 10));
2 of 2
2
So going from inside to the outer layer: You have Math.random which returns a random number between 0 and 1 You multiply that by Max - Min + 1 which is essentially the size of your allowed range Math.floor rounds down the result Those three, as you rightly pointed out, give you a random integer up to the requested limit. However, that limit is now the distance between your 2 parameters. For example, if you run that for min = 2 and max = 8, the random integer would be between 0 and 6. So, finally, we add the min to our result, offsetting the random integer in order to force it to land within our range.
🌐
Educative
educative.io β€Ί answers β€Ί how-to-generate-random-whole-numbers-in-javascript
How to generate random whole numbers in JavaScript
We can generate random whole numbers that fall between two specific ranges of two numbers. A *minimum (min) and a maximum number ( max) are defined to get this. ... The code above returns a whole number between 1 and 50.
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org β€Ί javascript
Basic JavaScript - Generate Random Whole Numbers within a Range - JavaScript - The freeCodeCamp Forum
June 19, 2021 - Math.floor(Math.random() * (max ... NT 10.0; Win64; x64; rv:108.0) Gecko/20100101 Firefox/108.0 Challenge: Basic JavaScript - Generate Random Whole Numbers within a Range Link to the challenge:...
🌐
freeCodeCamp
forum.freecodecamp.org β€Ί javascript
(HELP/LOST)Generate Random Whole Numbers within a Range
November 7, 2016 - Generate Random Whole Numbers within ... falls within a range of two specific numbers. To do this, we’ll define a minimum number min and a maximum number max....
🌐
freeCodeCamp
forum.freecodecamp.org β€Ί javascript
Creating a random whole number within a range
October 3, 2020 - Tell us what’s happening: Hello all. I have a question regarding creating a random whole number within a range. I can mentally follow what is happening up until (max - min + 1)) + min; My question is, I understand how this line of code creates a β€œceiling”(Max) for the number that will ...
🌐
Rust Programming Language
users.rust-lang.org β€Ί help
Fastest way to bulk generate random numbers within a range? - help - The Rust Programming Language Forum
October 12, 2024 - I'm trying to generate a list of random ints/floats, within a certain range, as fast as possible, eg `generate_x_ints(amount: u32, range: [u32; 2]) -> Vec' (doesn't necessarily have to be a vec).
🌐
freeCodeCamp
forum.freecodecamp.org β€Ί javascript
Generate Random Whole Numbers within a Range - solution not passing tests
December 22, 2022 - Hi, I can’t understand why my solution doesn’t pass this test: " randomRange should use both myMax and myMin , and return a random number in your range." Here is what I wrote and it seems to work just fine: function randomRange(myMin, myMax) { // Only change code below this line return Math.round(Math.random() * (myMax - myMin) + myMin); // Only change code above this line } challenge
Top answer
1 of 11
198

All the answers so far are mathematically wrong. Returning rand() % N does not uniformly give a number in the range [0, N) unless N divides the length of the interval into which rand() returns (i.e. is a power of 2). Furthermore, one has no idea whether the moduli of rand() are independent: it's possible that they go 0, 1, 2, ..., which is uniform but not very random. The only assumption it seems reasonable to make is that rand() puts out a Poisson distribution: any two nonoverlapping subintervals of the same size are equally likely and independent. For a finite set of values, this implies a uniform distribution and also ensures that the values of rand() are nicely scattered.

This means that the only correct way of changing the range of rand() is to divide it into boxes; for example, if RAND_MAX == 11 and you want a range of 1..6, you should assign {0,1} to 1, {2,3} to 2, and so on. These are disjoint, equally-sized intervals and thus are uniformly and independently distributed.

The suggestion to use floating-point division is mathematically plausible but suffers from rounding issues in principle. Perhaps double is high-enough precision to make it work; perhaps not. I don't know and I don't want to have to figure it out; in any case, the answer is system-dependent.

The correct way is to use integer arithmetic. That is, you want something like the following:

#include <stdlib.h> // For random(), RAND_MAX

// Assumes 0 <= max <= RAND_MAX
// Returns in the closed interval [0, max]
long random_at_most(long max) {
  unsigned long
    // max <= RAND_MAX < ULONG_MAX, so this is okay.
    num_bins = (unsigned long) max + 1,
    num_rand = (unsigned long) RAND_MAX + 1,
    bin_size = num_rand / num_bins,
    defect   = num_rand % num_bins;

  long x;
  do {
   x = random();
  }
  // This is carefully written not to overflow
  while (num_rand - defect <= (unsigned long)x);

  // Truncated division is intentional
  return x/bin_size;
}

The loop is necessary to get a perfectly uniform distribution. For example, if you are given random numbers from 0 to 2 and you want only ones from 0 to 1, you just keep pulling until you don't get a 2; it's not hard to check that this gives 0 or 1 with equal probability. This method is also described in the link that nos gave in their answer, though coded differently. I'm using random() rather than rand() as it has a better distribution (as noted by the man page for rand()).

If you want to get random values outside the default range [0, RAND_MAX], then you have to do something tricky. Perhaps the most expedient is to define a function random_extended() that pulls n bits (using random_at_most()) and returns in [0, 2**n), and then apply random_at_most() with random_extended() in place of random() (and 2**n - 1 in place of RAND_MAX) to pull a random value less than 2**n, assuming you have a numerical type that can hold such a value. Finally, of course, you can get values in [min, max] using min + random_at_most(max - min), including negative values.

2 of 11
36

Following on from @Ryan Reich's answer, I thought I'd offer my cleaned up version. The first bounds check isn't required given the second bounds check, and I've made it iterative rather than recursive. It returns values in the range [min, max], where max >= min and 1+max-min < RAND_MAX.

unsigned int rand_interval(unsigned int min, unsigned int max)
{
    int r;
    const unsigned int range = 1 + max - min;
    const unsigned int buckets = RAND_MAX / range;
    const unsigned int limit = buckets * range;

    /* Create equal size buckets all in a row, then fire randomly towards
     * the buckets until you land in one of them. All buckets are equally
     * likely. If you land off the end of the line of buckets, try again. */
    do
    {
        r = rand();
    } while (r >= limit);

    return min + (r / buckets);
}
🌐
DEV Community
dev.to β€Ί rthefounding β€Ί generate-random-whole-numbers-within-a-range-1pod
Generate Random Whole Numbers within a Range - DEV Community
April 27, 2021 - // If the values were myMin = 1, myMax= 9, one result could be the following: // Math.random() = 0.27934406917448573 // (myMax - myMin + 1) = 9 - 1 + 1 -> 9 // 0.27934406917448573 * 9 = 2.51409662257 // 2.51409662257 + 1 = 3.51409662257 // Math.floor(3.51409662257) = 3
🌐
Quora
quora.com β€Ί How-do-I-generate-3-random-whole-numbers-within-a-given-range-in-JavaScript
How to generate 3 random whole numbers within a given range in JavaScript - Quora
Answer (1 of 3): Below function which accept two integers(low and high range value) and it returns the array of three numbers between the given range. function randomNumberGenerator (low, high) { var a = []; a.push(Math.floor(Math.random() * ...
🌐
Manycalcs
manycalcs.com β€Ί home β€Ί math calculators β€Ί random number generator
Random Number Generator - Generate Custom Range Random Numbers | ManyCalcs
Each click of "Generate" produces an independent random number. JavaScript can safely handle integers up to 2^53 - 1 (about 9 quadrillion). This generator works with any integer range within this limit. For most practical purposes, any reasonable range will work perfectly. Very large ranges maintain uniform distribution. This tool generates integers (whole ...
🌐
freeCodeCamp
forum.freecodecamp.org β€Ί javascript
Help me understand Generate Random Whole Numbers within a Range Challenge
September 4, 2020 - HI I am stuck understanding this challenge because it is complicated a little bit when it comes to understanding this line return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin; I need help to understand this line and how it works exactly
🌐
Github-wiki-see
github-wiki-see.page β€Ί m β€Ί antoniojvargas β€Ί FreeCodeCamp β€Ί wiki β€Ί Generate-Random-Whole-Numbers-within-a-Range
Generate Random Whole Numbers within a Range - antoniojvargas/FreeCodeCamp GitHub Wiki
function randomRange(myMin, myMax) { return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin; // Change this line } // Change these values to test your function var myRandom = randomRange(5, 15);