For most implementations, Math.random() is sufficient. For instance, when it's used to generate random numbers for game play. It would not be suitable for cryptographic applications. The primary criticism is that it's deterministic, and not "truly random". Some alternatives are Web Crypto API and Random.js . Answer from SouthCape on reddit.com
🌐
MDN Web Docs
developer.mozilla.org β€Ί en-US β€Ί docs β€Ί Web β€Ί JavaScript β€Ί Reference β€Ί Global_Objects β€Ί Math β€Ί random
Math.random() - JavaScript - MDN Web Docs
The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range β€” which you can then scale to your desired range. The implementation selects the initial seed to the random ...
🌐
W3Schools
w3schools.com β€Ί js β€Ί js_random.asp
JavaScript Random
Math.random() returns a floating-point number between 0 (inclusive) and 1 (exclusive).
Discussions

How bad is Math.random()?
For most implementations, Math.random() is sufficient. For instance, when it's used to generate random numbers for game play. It would not be suitable for cryptographic applications. The primary criticism is that it's deterministic, and not "truly random". Some alternatives are Web Crypto API and Random.js . More on reddit.com
🌐 r/learnjavascript
30
12
February 24, 2023
Generating random whole numbers in JavaScript in a specific range - Stack Overflow
I've created a JSFiddle if anyone ... method: jsfiddle.net/F9UTG/1 2013-06-05T13:56:07.693Z+00:00 ... IonuΘ› G. Stan Β· IonuΘ› G. Stan Over a year ago Β· @JackFrost yeah, that's right. You're not dumb, you're just learning :) 2016-01-27T14:19:58.993Z+00:00 ... This question is old, but understanding this answer took me way too much time O.o, I think expanding math.random on next JavaScript ... More on stackoverflow.com
🌐 stackoverflow.com
How does Math.random() work in javascript? - Stack Overflow
This has been pointed out to us, and having understood the problem and after some research, we decided to reimplement Math.random based on an algorithm called xorshift128+. It uses 128 bits of internal state, has a period length of 2128 - 1, and passes all tests from the TestU01 suite. More on stackoverflow.com
🌐 stackoverflow.com
Basic JavaScript - Generate Random Whole Numbers with JavaScript
Tell us what’s happening: The instructions for this lesson ask you to use the Math.floor(Math.random()) * N to generate and return a random whole number between 0 and 9 When I return Math.floor(Math.random()*9) it is not accepted. The error says " You should have multiplied the result of ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
April 18, 2023
🌐
Math.js
mathjs.org β€Ί docs β€Ί reference β€Ί functions β€Ί random.html
math.js
math.random() // returns a random number between 0 and 1 math.random(100) // returns a random number between 0 and 100 math.random(30, 40) // returns a random number between 30 and 40 math.random([2, 3]) // returns a 2x3 matrix with random numbers between 0 and 1
🌐
V8
v8.dev β€Ί blog β€Ί math-random
There’s Math.random(), and then there’s Math.random() Β· V8
Math.random() is the most well-known and frequently-used source of randomness in JavaScript. In V8 and most other JavaScript engines, it is implemented using a pseudo-random number generator (PRNG). As with all PRNGs, the random number is derived from an internal state, which is altered by ...
🌐
GitHub
github.com β€Ί ckknight β€Ί random-js
GitHub - ckknight/random-js: A mathematically correct random number generator library for JavaScript. Β· GitHub
A mathematically correct random number generator library for JavaScript. - ckknight/random-js
Starred by 616 users
Forked by 51 users
Languages Β  TypeScript 94.8% | JavaScript 5.2%
Find elsewhere
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;
Top answer
1 of 5
35

This answer is outdated. See this answer for a more up-to-date explanation.

Math.random() returns a Number value with a positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy.

Here's V8's implementation:

uint32_t V8::Random() {

    // Random number generator using George Marsaglia's MWC algorithm.
    static uint32_t hi = 0;
    static uint32_t lo = 0;

    // Initialize seed using the system random(). If one of the seeds
    // should ever become zero again, or if random() returns zero, we
    // avoid getting stuck with zero bits in hi or lo by reinitializing
    // them on demand.
    if (hi == 0) hi = random();
    if (lo == 0) lo = random();

    // Mix the bits.
    hi = 36969 * (hi & 0xFFFF) + (hi >> 16);
    lo = 18273 * (lo & 0xFFFF) + (lo >> 16);
    return (hi << 16) + (lo & 0xFFFF);
}

Source: http://dl.packetstormsecurity.net/papers/general/Google_Chrome_3.0_Beta_Math.random_vulnerability.pdf

Here are a couple of related threads on StackOverflow:

  • Why is Google Chrome's Math.random number generator not *that* random?
  • How random is JavaScript's Math.random?
2 of 5
15

See There's Math.random(), and then there's Math.random():

Until recently (up to version 4.9.40), V8’s choice of PRNG was MWC1616 (multiply with carry, combining two 16-bit parts). It uses 64 bits of internal state and looks roughly like this:

uint32_t state0 = 1;
uint32_t state1 = 2;
uint32_t mwc1616() {
  state0 = 18030 * (state0 & 0xffff) + (state0 >> 16);
  state1 = 30903 * (state1 & 0xffff) + (state1 >> 16);
  return state0 << 16 + (state1 & 0xffff);
}

The 32-bit value is then turned into a floating point number between 0 and 1 in agreement with the specification.

MWC1616 uses little memory and is pretty fast to compute, but unfortunately offers sub-par quality:

  • The number of random values it can generate is limited to 232 as opposed to the 252 numbers between 0 and 1 that double precision floating point can represent.
  • The more significant upper half of the result is almost entirely dependent on the value of state0. The period length would be at most 232, but instead of few large permutation cycles, there are many short ones. With a badly chosen initial state, the cycle length could be less than 40 million.
  • It fails many statistical tests in the TestU01 suite.

This has been pointed out to us, and having understood the problem and after some research, we decided to reimplement Math.random based on an algorithm called xorshift128+. It uses 128 bits of internal state, has a period length of 2128 - 1, and passes all tests from the TestU01 suite.

The new implementation landed in V8 4.9.41.0 within a few days of us becoming aware of the issue. It will become available with Chrome 49. Both Firefox and Safari switched to xorshift128+ as well.

The xorshift128+ implementation looks like this:

static inline void XorShift128(uint64_t* state0, uint64_t* state1) {
  uint64_t s1 = *state0;
  uint64_t s0 = *state1;
  *state0 = s0;
  s1 ^= s1 << 23;
  s1 ^= s1 >> 17;
  s1 ^= s0;
  s1 ^= s0 >> 26;
  *state1 = s1;
}
🌐
freeCodeCamp
forum.freecodecamp.org β€Ί javascript
Basic JavaScript - Generate Random Whole Numbers with JavaScript - JavaScript - The freeCodeCamp Forum
April 18, 2023 - Tell us what’s happening: The instructions for this lesson ask you to use the Math.floor(Math.random()) * N to generate and return a random whole number between 0 and 9 When I return Math.floor(Math.random()*9) it is…
🌐
DEV Community
dev.to β€Ί jesterxl β€Ί seeing-javascript-mathrandom-not-be-so-random-1235
Seeing JavaScript Math.random Not Be So Random - DEV Community
February 5, 2023 - I hope that the frequencies my JS generates can demonstrate that the distribution of random numbers between 1 and 6 is fairly even, rather than being biased. Although the PRNG in use cannot be truly random, it does a good enough job. I think this is basically what your Monte Carlo simulation tells you, too. It's not saying you'll get 3.5, it's saying the average is 3.5. ... Not sure why Math.random eventually settling around the theoretical mean would mean it is not random?
🌐
Programiz
programiz.com β€Ί javascript β€Ί library β€Ί math β€Ί random
JavaScript Math random()
The Math.random() function returns a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).
🌐
Reddit
reddit.com β€Ί r/learnprogramming β€Ί generate a random number within a range - how does the math work?
r/learnprogramming on Reddit: Generate A Random Number Within A Range - How Does the Math Work?
February 4, 2022 -

Hi all,

I'm learning JS through FCC and it's going okay so far. I'm not a very mathematically inclined person, however, so I struggle with some concepts.

I'm struggling to understand how the following code works;

Math.floor(Math.random() * (max - min + 1)) + min

I tried writing out an example on paper and used 10 and 5 as max and min respectively.

Math.floor(Math.random() * (10 - 5 + 1)) + 5

wouldn't this mean that I can get numbers higher than the max though? Say I get a randomly generated 0.99; well 0.99 * (6) + 5 = 10.94 which is greater than my max of 10?

Am I doing this wrong?

🌐
HackerNoon
hackernoon.com β€Ί how-does-javascripts-math-random-generate-random-numbers-ef0de6a20131
How does JavaScript’s Math.random() generate random numbers? | HackerNoon
March 12, 2018 - Open up your dev tools’ (Mac: cmd + option + i / Windows: ctrl + shift + i), go to the Console, type Math.random() , and hit return.
🌐
Udacity
udacity.com β€Ί blog β€Ί 2021 β€Ί 04 β€Ί javascript-random-numbers.html
Creating Javascript Random Numbers with Math.random() | Udacity
September 27, 2022 - So, to create a random number between 0 and 10: ... Math.random() is a useful function, but on its own it doesn’t give programmers an easy way to generate pseudo-random numbers for specific conditions.
🌐
Codecademy
codecademy.com β€Ί forum_questions β€Ί 5020be4d3a51800002015ebe
Math.floor and Math.random | Codecademy
function rand(min, max) { return Math.random() * (max - min) + min; } This will get you a random float between min and max not including max. There are better ways to do this (so that, if only one number is given, it’s assumed to be max and 0 the min), but none this simple. ... I’ve edited my question to give a simple rand implementation in JS.
🌐
Vultr Docs
docs.vultr.com β€Ί javascript β€Ί standard-library β€Ί Math β€Ί random
JavaScript Math random() - Generate Random Number | Vultr Docs
November 29, 2024 - The Math.random() method in JavaScript is an essential tool for generating random numbers. This function returns a floating-point, pseudo-random number in the range from 0 (inclusive) to 1 (exclusive), which you can then scale to your desired range.
🌐
Keploy
keploy.io β€Ί home β€Ί community β€Ί how to generate random numbers in javascript
How to Generate Random Numbers in JavaScript | Keploy Blog
November 1, 2024 - Learn to generate random numbers, integers, Booleans in JavaScript for different scenarios, from basic to advanced techniques.
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί javascript-math-random-method
JavaScript Math random() Method - GeeksforGeeks
July 15, 2024 - The JavaScript Math.random() function gives you a random number between 0 and just under 1. You can use this number as a base to get random numbers within any range you want.