Random Number Generator
Math.random()
The Math.random() function returns an unspecified floating-point number that is in the range 0 to not more than one (inclusive of zero, but not 1) with 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
Note: Math.random() does not offer cryptographically secure random numbers. Avoid using them for any security-related purpose. 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 it is a pseudo random number between 0 (inclusive) to 1. (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 exceptionally high bounds are chosen (2^53 or greater) there is a possibility in very very rare circumstances to calculate the normally-excluded upper bound.
Getting the random number between 0 (inclusive) and 1 (exclusive)
function getRandom() return Math.random();
Copy to Clipboard
Finding a random number between two values
This example returns a random number between the specified values. The returned value is no less than (and could be more than) min, and is less than (and not the same as) max.
function getRandomArbitrary(min, max) return Math.random() * (max - min) + min;
Copy to Clipboard
Finding a random integer that is between two values
This code returns a random integer with the specified values. It isn't lower than min (or the next integer that is greater than min if min isn't an integer) and is lower than (but less 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 achieve this, however doing this could cause the random numbers to follow a non-uniform distribution, which might not be suitable for your requirements.
Finding a random integer that is between two values inclusive
The function above, the getRandomInt() function above is inclusive at the minimum, it's not inclusive at the top. What happens if you require outcomes that are inclusive both at the minimum and the 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