0

There are posts in SO on how to generate a random number in Javascript. One common solution is:

Math.floor(Math.random() * (max - min + 1)) + min;

But if I set my min to 0 and max to 3 and refresh my web app, the vast majority of times this function will return 0. There is clearly no even distribution on the randomness generated.

Is there a better way than doing it like this?

Johann
  • 27,536
  • 39
  • 165
  • 279
  • 1
    There are very few "true" random generators, especially in clientside JS, but there are better ones, and this has been asked many time before – adeneo Sep 10 '17 at 07:02
  • >> the vast majority of times this function will return 0. There is clearly no even distribution on the randomness generated This is incorrect, as you can see by running a simple test: function rng(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } let a = new Array(10).fill(0); for (let i = 0; i < 10000; i += 1) { let n = rng(0, 9); a[n] += 1; } console.log(a); – Alex Undefined Sep 10 '17 at 07:30
  • There is an crypto API in JavaScript which you might be interested in. – Derek 朕會功夫 Sep 10 '17 at 23:32

0 Answers0