Random Number Generator
Math.random()
The Math.random() function returns a floating-point, pseudo-random number that is in the range 0 to greater than (inclusive of 0 but not 1) with an approximately uniform distribution over the interval -- which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.https://interactive-examples.mdn.mozilla.net/pages/js/math-random.html
Notice: Math.random()
does not offer cryptographicallysecure random numbers. Avoid using them in connection with security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues()
method.
Syntax
Math.random()
Copy to Clipboard
Value of Return
A floating-point, virtual random number between 1
(inclusive) (inclusive) and one (exclusive).
Examples
Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random()
itself) aren't exact. If extremely large limits are selected (2^53 or higher) it is possible in very extremely rare situations to calculate the upper bound that is usually excluded.
Finding an random number between 0 (inclusive) and 1 (exclusive)
function getRandom() return Math.random();
Copy to Clipboard
Finding the random numberbetween two values
This example gives an random number between the specified values. The returned value is no lower than (and could be equal to) min
, and is smaller than (and not equal) max
.
function getRandomArbitrary(min, max) return Math.random() * (max - min) + min;
Copy to Clipboard
A random integer is a number that lies between two values
This code returns an indeterminate integer within the range of values you specify. The result is not lower than min
(or the next number that is greater than min
when min
isn't an integer), and is less than (but not greater than) max
.
function getRandomInt(min, max) min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
Copy to Clipboard
Notice: It might be tempting to utilize Math.round()
to accomplish that, but doing so will cause that your random numbers to follow a non-uniform distribution, which may not be acceptable for your requirements.
Finding a random integer that is between two values inclusive
Even though the findRandomInt()
function above is inclusive at minimum, it's not inclusive at its maximum. How do you get outcomes that are inclusive at both the minimum and at the highest? The getRandomIntInclusive()
function below accomplishes that.
function getRandomIntInclusive(min, max) min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is inclusive
Comments
Post a Comment