Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Mihai Badic
4,246 PointsAre the odds actually correct in the number generator formula?
OK so I have question regarding the odds of getting the numbers 1 to 6 in the random generator formula used in this course, as it seems to me that something is wrong (ie. some numbers are more likely to be spit out than others). I hope I am wrong, here goes:
Math.random() generates a number that is between 0 and 1 but not including 1, which for simplicity's sake I will deal with as if it has only 1 decimal in my description below, I don't think this affects the reasoning?
Imagine that what Math.random() generated was 0.1: the result of the formula (after we multiply by 6, then floor down the result to the first integer below and add 1) will be 1. This is because 0.6 rounds down to 0 and then we add the 1.
If the result was 0.2, then the result will be 2. (1.2 rounds down to 1 and then we add the 1)
The problem starts here as it is the same for 0.3 (as 1.8 floors down to 1 again), so already the chances of getting a 2 as the final result are greater.
I will now skip the explanation for the following numbers.
0.4 -> 3 0.5 -> 4 0.6 -> 4 0.7 -> 5 0.8 -> 5 0.9 -> 6
As you can see, the chances of getting 1, 3 and 6 are smaller than getting 2, 4 and 5.
Or I am completely wrong about how important the other decimals are.
Thank you and apologies if this was silly.
3 Answers
Falk Schwiefert
8,706 PointsJason Anders
Treehouse Moderator 145,863 PointsHey Mihai,
The flaw in your logic lies in using only one decimal place. Falk Schwiefert provides an excellent link that demonstrates the difference. (Thank you Falk!)
Yes, .3 => 1.8 which round down to 1 and give you 2 (+1), but .3456825 give you 2.074095 which floors to 2 and gives you 3 (+1). So when you factor in the fact that it could go to many decimal places, it makes a huge difference and actually gives you a very equal distribution of 1 through 6 over hundreds of rolls.
So, yes. The odds are correct.
:)
Mihai Badic
4,246 PointsThanks Falk Schwiefert & Jason Anders !
Jason Anders
Treehouse Moderator 145,863 PointsJason Anders
Treehouse Moderator 145,863 PointsGood link... Thank you! :)
Mihai Badic
4,246 PointsMihai Badic
4,246 PointsGreat link!