4

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

6
  • What is getRandomInt? Is that from a library? Commented Mar 2, 2022 at 18:24
  • 1
    accidentally added the function name to the question, that's what the getRandomInt() is. Commented Mar 2, 2022 at 18:31
  • I’m voting to close this question because the edits to the question make the comments and answer no longer relevant. Commented Mar 2, 2022 at 18:32
  • I think the built-in choices are (pseudo-random) Math.random and (stronger but still pseudo random) Crypto.getRandomValues. I've not needed more than Math.random so far. Commented Mar 2, 2022 at 18:37
  • In what possible way could math.round() be considered a random number generator? Commented Mar 3, 2022 at 0:27

3 Answers 3

5

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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.