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 trialjohn larson
16,594 Pointswhy does one of these lines of js return a zero sometimes but the other does not?
Math.floor(Math.random() * (12-6 + 1))
4
Math.floor(Math.random() * (12-6) + 1)
6
The first one will occasionally return a zero. I get that it has to do with where +1 is in the parenthesis
...but why?
2 Answers
Robert Richey
Courses Plus Student 16,352 PointsHi John,
It's because Math.random()
returns a floating-point number between 0 and 0.999...
You can think of Math.random() * n as returning a floating-point number within the interval [0, n), where 0 is inclusive and n is exclusive.
// Example 1
Math.floor(Math.random() * (12-6 + 1));
Math.floor(Math.random() * 7);
// Math.random() * 7 = a floating-point number within the interval [0, 7)
// by flooring this value, you'll get a whole number from 0 - 6
// Example 2
Math.floor(Math.random() * (12-6) + 1);
Math.floor(Math.random() * 6 + 1);
// following the order of operations, multiplication comes first
// Math.random() * 6 = a floating-point number within the interval [0, 6)
// then, +1 to this value resulting in a floating-point number within the interval [1, 7)
// by flooring this value, you'll get a whole number from 1 - 6
Edit: changed terminology from 'set notation' to 'interval notation'; fixed the order of brackets and parens to correctly represent inclusive and exclusive.
Hope this helps,
Cheers
john larson
16,594 PointsWow, Robert Thank you. When I first saw your answer I thought I wouldn't get it. After looking at the example in the code you sent, it just made sense. Thank you again for taking the time to explain it to me.
Robert Richey
Courses Plus Student 16,352 PointsAwesome, I'm glad it helped :)