Is math.random()
a good method for a random/pseudo-random number generator?

- 33
- 7
-
What is getRandomInt? Is that from a library? – James Mar 02 '22 at 18:24
-
accidentally added the function name to the question, that's what the getRandomInt() is. – Veillax135 Mar 02 '22 at 18:31
-
I’m voting to close this question because the edits to the question make the comments and answer no longer relevant. – devlin carnate Mar 02 '22 at 18:32
-
I think the built-in choices are (pseudo-random) Math.random and (stronger but still pseudo random) [Crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues). I've not needed more than Math.random so far. – James Mar 02 '22 at 18:37
-
In what possible way could `math.round()` be considered a random number generator? – President James K. Polk Mar 03 '22 at 00:27
-
sorry all, had a typo – Veillax135 Mar 04 '22 at 02:10
3 Answers
getRandomInt() random() is a pseudo-random number as no computer can generate a truly random number, that exhibits randomness over all scales and over all sizes of data sets.

- 17
- 2
The thing is - only software random number generators cannot provide true random numbers, only approximations to them.
The standard JS way via Math.random()
is sufficient for most cases.
//standard JS approach
function random(min,max) {
return Math.floor((Math.random())*(max-min+1))+min;
}
This can be improved a bit if you use the Crypto API. by Kamil Kiełczewski
//using crypto function
function rand(a, b) {
return a+(b-a+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
}
But the purpose of the numbers is also important. Because both approaches produce consecutive equal numbers in the sequence. If you use random numbers to output dummy images in the prototype phase of a project, for example, you would have identical images one after the other, which you would rather avoid. For this purpose, good random numbers would be those without producing the same number twice in a row. This can only be done by storing the last number and recursion.
//random sequenz without last number repetition
let last = -1
function rand(a, b) {
const rnd = a+(b-a+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
if (rand === last) {
return rand(a, b)
} else {
last = rnd
return rnd
}
}

- 12,361
- 6
- 53
- 72
The Math.round()
function returns the value of a number rounded to the nearest integer.
console.log(Math.round(0.9));
// expected output: 1
console.log(Math.round(5.95), Math.round(5.5), Math.round(5.05));
// expected output: 6 6 5
console.log(Math.round(-5.05), Math.round(-5.5), Math.round(-5.95));
// expected output: -5 -5 -6
I would say the best method for random numbers is math.random(). good luck!

- 708
- 2
- 6
- 17