Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Random index does not return random index in Confirm #651

Closed
webmaster128 opened this issue Mar 30, 2018 · 1 comment
Closed

Random index does not return random index in Confirm #651

webmaster128 opened this issue Mar 30, 2018 · 1 comment
Assignees

Comments

@webmaster128
Copy link
Contributor

webmaster128 commented Mar 30, 2018

Expected behaviour

From naming and code comments, this function should return a random index:

const indexByRand = num => Math.floor(num * (words.length - 1));
indexByRand(Math.random());

Actual behaviour

It does not include the last index. This is because Math.random() is strictly < 1.0 and thus num * (words.length - 1) < (words.length - 1) and which makes words.length - 1 impossible.

Even if Math.random() would include 1.0, the last index would be chosen significantly less often then the other indices because only the value 1.0 leads to the last index where the other indices have a whole interval.

Steps to reproduce

Simulate using this node rnd_test.js:

const words_length = 12;
const indexByRand = num => Math.floor(num * (words_length - 1));
const randomIndex = () => indexByRand(Math.random());

let statistics = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // number of occurrence for index 0 to 11.

for (let i = 0; i < 10000000; i++) {
    statistics[randomIndex()] += 1;
}

console.log(statistics);

prints

[ 907928,
  910979,
  908350,
  910128,
  909866,
  909620,
  907623,
  908070,
  908512,
  908911,
  910013,
  0 ]
@webmaster128
Copy link
Contributor Author

When changing the function randomIndex like this, we get proper results. rnd_test.js:

const words_length = 12;
const randomIndex = () => Math.floor(Math.random() * words_length);

let statistics = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

for (let i = 0; i < 10000000; i++) {
    statistics[randomIndex()] += 1;
}

console.log(statistics);

prints

[ 834966,
  833113,
  832922,
  832819,
  832974,
  833467,
  833171,
  833465,
  833986,
  833847,
  833177,
  832093 ]

This is what StackOverflow also agrees on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants