Random Number Generator
Math.random()
The Math.random() function returns an unspecified floating-point number in the range 0 - not more than one (inclusive of 0, but not exactly 1) with approximately uniform distribution over the range -- which you could 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 provide cryptographicallysecure random numbers. Do not use 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 pseudo- random number between the numbers 0 (inclusive) to 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 bounds are chosen (2^53 or greater), it's possible in extremely rare cases to calculate the typically-excluded upper limit.
Getting the random number between 0 (inclusive) and 1 (exclusive)
function getRandom() return Math.random();
Copy to Clipboard
Getting the random numberbetween two values
This example returns an random number between the specified values. The returned number is not lower than (and might be higher than) min, and is not greater than (and is not equivalent to) max.
function getRandomArbitrary(min, max) return Math.random() * (max - min) + min;
Copy to Clipboard
The process of generating a random integer between two values
This example gives an undetermined integer that is between the values specified. It isn't lower than min (or the next integer greater in value than min when min isn't an integer) and is lower than (but not exactly equal to) 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
Note: It might be tempting to utilize Math.round() for this purpose, however doing so would cause you to have your randomly generated numbers to follow a non-uniform distribution, which may not be appropriate for your needs.
Getting a random integer between two values inclusive
While the getRandomInt() function above is inclusive at the minimum, it's exclusionary at the maximum. What happens if outcomes that are inclusive both at the minimum and maximum? 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