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

JavaScript

brandonlind2
brandonlind2
7,823 Points

Will this RandomNumber generation do the same thing without future problems or am I missing something?

The teacher taught when generating random numbers between two values to use Math.floor(Math.random() * (top - lower + 1)) + lower. I keep making a typo though and typing it this way Math.floor(Math.floor(Math.random() * (top - lower) + lower) + 1; but this seems to work fine. Is the way to generate number obsolute, if I dont correct this habbit will it cause problems in the future or can I continue to write this way? Also is the + 1 one necessary when generating two values? I thought the + 1 was originally to keep the random number from being 0, but if you're setting the lower number it shouldnt already be zero.

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hey Brandon,

For the first part of your question, mathematically it doesn't make a difference if you add lower first or after adding the one. For me, I think just for style and readability of the code, it is 'nicer' adding the lower at the end, but that is entirely up to you.

For the second part, adding the one is necessary. Math.random() generates a random float from (and including) Zero up to (but not including) One.

Because of the float that will be generated, the closest you can get to One is 0.999999999 (example). So, because you will never get a One, and you are using Math.floor(), it is impossible for the top number in the range to ever come up (because you always round down).

Example. Range of 2 to 10. Math.random() generates 0.925734 which is multiplied by 8 (top - bottom) to get 7.405872. If we don't add the One and just add the lower range of 2, we get 9.405872 and we Math.floor() to 9. Now if we add the One we get 10.405872 and with Math.floor(), now we get 10 instead. So without adding One, you can run the generator an infinite number of times, but you will never generate a 10 (top value).

I hope this makes sense and helps your understanding. Keep Coding! :)

brandonlind2
brandonlind2
7,823 Points

That makes sense. Thanks, I appreciate the in depth explanation!