Skip to content

More information about randomInt being biased? #13

@voltrevo

Description

@voltrevo

I looked sideways at your readme when you said that:

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

produced a biased/non-uniform distribution. Math.random()'s contract is to produce a random number from a uniform distribution on [0, 1), and given that contract, I don't see how randomInt incorrectly transforms that to a uniform distribution of the integers in [min, max). It's a bit unclear whether you're suggesting that Math.random() fails to be uniformly distributed on [0, 1). Are you suggesting that? If so, which browsers are affected?

I tried this on Chrome 45:

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

var tallies = [0, 0, 0, 0, 0];

for (var i = 0; i !== 1000000; i++) {
  tallies[randomInt(0, 5)]++;
}

console.log(tallies);

And got this output:

[199601, 200204, 200379, 200016, 199800]

So it at least appears to be right. Could you elaborate please?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions