Can Math.random() = 1?
I was wondering can Math.random() = 1 or 0?
score = Math.floor(Math.random()*10+1);
console.log(score);
My concern is that if it can = 1 then the code has the potential to have an exception in the method of teaching for describing how to randomly generated number between 0 and 10. I.e. if Math.random() does = 1 and you then time that by 10 and + 1 which equals 11. When you floor the number you would get 11 NOT 10 (although I understand this would be a rare case).
Answer 50633772b0b7f50002008668
Short answer: No, in both cases. Math.random() can never generate 0 because it starts with a non-zero seed. Set the seed to zero, the function does not work, or throws an error.
A random number generator always returns a value between 0 and 1, but never equal to one or the other. Any number times a randomly generated value will always equal to less than that number, never more, and never equal. Math.floor(Math.random() * 10) will always return 0 to 9. So you have no worries of a special case cropping up. It won’t.
3 comments
Correction: Math.random() can, on the slimmest of chances, generate a zero, though this is most probably unlikely to ever happen. This is the understanding I’ve always had, and why the wording, ‘between 0 and 1’ can be so easily misunderstood to mean, not equal to zero or 1. In cases where I have wanted an equal probability of zero and any other numbers between 0 and an upper bound integer, I’ve always used Math.floor. For numbers 0 to 9, there is a 10% chance of generating a zero, 0 to 99, a 1% chance, 0 to 999 a 0.1% chance. When we consider that Math.random generates a double float between 0 and <1, we can reason that P(E) = 0 is a very tiny probability, at best.
FINALLY explained well. Thank you O_O!!
Addendum: A simple while statement is enough to prove that Math.random() can and will eventually yield zero. Just keep clicking ‘Wait’ if the loop times out. var c = 0; while (Math.random() !== 0) {c++;} console.log("0 reached in "+c+" iterations".
Answer 507d5ffb0a00a00200002292
I actually was bothered by this, so I looked into it. Math.random() CAN equal zero, but cannot equal one. This is, I imagine, to avoid exactly this concern. By using Math.floor(), we can ensure the odds of getting any given whole number are exactly the same.
Popular free courses
- In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.
- Beginner Friendly.4 Lessons
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.11 Lessons
- Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.
- Beginner Friendly.6 Lessons