You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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);
Expected behaviour
From naming and code comments, this function should return a random index:
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 makeswords.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
:prints
The text was updated successfully, but these errors were encountered: