0

I'm using the following code

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

to come up with a random number. However, this is not giving me a random distribution. Does anyone know a better way to come up with a random number in javascript?

Chris Hansen
  • 7,813
  • 15
  • 81
  • 165
  • 2
    How do you know it's not giving you a random distribution? Did you perform a chi-square test on the results? How many times did you call it? – Barmar Feb 15 '17 at 23:48
  • 1
    `Math.floor(Math.random())` will practically always be `0` – Tamas Hegedus Feb 15 '17 at 23:51
  • 1
    You've an extra parenthesis in your source - it won't compile. Presumably it's the second one in `.random())`, otherwise what @TamasHegedus says applies – CupawnTae Feb 15 '17 at 23:53

1 Answers1

0

You have an error in your code, Math.floor(Math.random()) * should be Math.floor(Math.random() *. That aside, if you look at a large enough sample size, for example 100,000, it looks pretty close to even to me.

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var total = 0, count = 100000;
for(var i = 0; i<count; i++){
  total += getRandomInt(1,100);
}

console.log("Expected: 50.5");
console.log("Actual: "+(total / count));
Travis J
  • 81,153
  • 41
  • 202
  • 273