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

Tommy Bo
Tommy Bo
632 Points

What is the meaning and how does the equation (highnumber - lownumber + 1) make sense?

I don't understand the equation:

Math.floor( Math.random () * (highInput - lowInput ) + lowInput );

Why and how does this make sense mathematically? So far I reason that because we want to find a number between 3-7, let's say, we first have to find out the number of numbers in between the lowest and highest, otherwise known as the difference.

Then, after finding that out, we multiply 4 with the randomly generated number, which is a number including 0 up to but not including 1. So 4 * 0.99 = 4.99.

We round that number down to 4 and add the lowest input of 3 which produces 7. So we have a number between 3 and 7.

Is there another way to solve this and did I get the meaning right?

Thank you and much appreciated.

1 Answer

Blaize Pennington
Blaize Pennington
13,879 Points

So you are missing a 1.

Math.floor (Math.random() * (highInput - lowInput + 1) + lowInput )
Math.floor ( Math.random() * (7 - 3 + 1) + 3);
// Parentheses first
Math.floor ( Math.random() * (5) + 3);
// Then multiply
// lowest possible answer 0 * 5
Math.floor ( 0 + 3) //results in 3 and gets rounded down to 3.
// highest possible answer .99999999999999 * 5
Math.floor ( 4.99999999 + 3 ) // results in 7.999999999 which gets rounded down to 7.
Tommy Bo
Tommy Bo
632 Points

Thank you!