Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best choice for javascript random number generator

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

like image 690
Veillax135 Avatar asked Nov 14 '25 09:11

Veillax135


1 Answers

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
  }
}
like image 173
Hexodus Avatar answered Nov 17 '25 09:11

Hexodus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!