Is math.random()
a good method for a random/pseudo-random number generator?
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
}
}