Random Number Generator
Math.random()
The Math.random() function returns an unspecified floating-point number within the range of 0 to less than 1 (inclusive of 0 but not exactly 1) with an approximately uniform distribution across that space -- 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. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.
Syntax
Math.random()
Copy to Clipboard
Return value
A floating-point, also known as a random number between (0 (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 greater) there is a possibility in very rare cases to calculate the typically-excluded upper limit.
Finding an random number between 0 (inclusive) and 1 (exclusive)
function getRandom() return Math.random();
Copy to Clipboard
Finding an random numberbetween two values
This example will return a random number between the specified values. The result isn't lower than (and may possibly equal) min, and is smaller than (and not the same as) max.
function getRandomArbitrary(min, max) return Math.random() * (max - min) + min;
Copy to Clipboard
Getting a random integer between two values
This code returns a random integer that is between the values specified. The value can't be less than min (or the next number that is greater than min in the event that min isn't an integer), and is less 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 use Math.round() to achieve this, however doing this could result in the random numbers to follow a non-uniform distribution, which may not be suitable for your purposes.
The process of generating a random integer between two values, inclusive
Even though the obtainRandomInt() function above is inclusive at minimum, it's exclusionary at the top. How do you get the results to be 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