Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Functions Arrow Functions Function Challenge Solution

Can someone please explain the actual equation? Thank you :)

Hi,

I understand why and how the code works but maths was never my strong point and I'm struggling to understand the actual equation - can someone please break it down?

// I understand the code just not the equation.

const getRandomNumber = (low, high) => Math.floor(Math.random() * ((high - low)+1) + low);

Sometimes if you really struggling to memorize something, and at the same time you can let it go, so better let it go and move on. Sometimes I really want to know how things work in detail and why they are writing like this, but this would result in a headache and waste of a lot of time. Back to this video, the teacher explained that if you don't understand it is okay, you have the code for it.

That's my advice.

7 Answers

Steven Parker
Steven Parker
216,136 Points

Think of "high - low + 1" as the range, or how many different numbers the function can produce. So when you multiply random() by the range you get a number in that spread, but starting from 0.

Then when you add the lower number, it shifts that range up from 0 to where you want it.

The "floor" function just chops off any fractional part, leaving a whole number.

Hi Steven,

Thank you for the explanation although I'm still really struggling to work it out! I'm sure it is simple but I can't get my head around it - feeling stupid!

Steven Parker
Steven Parker
216,136 Points

Perhaps an example will help:
Say you want a random number between 5 and 8 (inclusive). The possible values are 5, 6, 7, and 8. So that's a range of 8 - 5 + 1 or  4  numbers.

Then if you multiply random() by 4, you'll get a number between 0 and 3, likely with some fractional part.

Now if you add the lower number (5), you'll have a number somewhere between 5 and 8 (plus some fraction).

Finally, the "floor" function cuts of the fraction leaving just a whole number between 5 and 8.

Does that make it more clear?

I am also confused. I understand how you get the range but what I don't understand is why we add 1 to upper - lower and also why you add lower in the end of the line. Wouldnt the code (upper - lower + 1) give a single number so why would we add lower to that single number.

Steven Parker
Steven Parker
216,136 Points

Look at the example again. If you want a number between 5 and 8, that's 4 possible numbers (5, 6, 7, or 8). But 8 - 5 is only 3, so you have to add the 1 to get 4. So the formula for the range is upper - lower + 1.

Then when you multiply random() by the 4 you get a number from 0 to 3 (ignoring the fractional part that "floor" will knock off). So adding the 5 (the lower) moves the result number from 0 to 3 up to 5 to 8.

Diane Bond
Diane Bond
8,011 Points

Great explanation!

I'm using my fingers here :-) if i have range 10 to 4 for example i would count 4, 5, 6, 7, 8, 9, and 10, so instead of thinking 10 - 4 = 6 in the range case it is actually 7! Is that right?

Steven Parker
Steven Parker
216,136 Points

That's right, the formula is upper - lower + 1, so in this case 10 - 4 + 1 which is 7.

2pd
2pd
8,123 Points

I still can't understand why we are subtracting the lower number from the higher number ... I don't understand what that has to do with the range.

Math.floor(Math.random() * (upper - lower + 1)) + lower;

Why + 1?

Let's say upper has the value of 10, while lower has the value of 5. In the context of the function we then want to generate a random number between 5 and 10 — so either 5, 6, 7, 8, 9 or 10.

5, 6, 7, 8, 9 and 10 are 6 different possibilities, but in the context of the equation 10 - 5 = 5. This means we're one short, hense we add 1. The + 1 basically ensures that our values are inclusive ie. both 5 and 10 can be one of the random numbers generated, as intended.

Why + lower?

We add on the lower value to ensure the number generated has the minimum value of the value assigned to lower and similarly aligns the generated number to the value assigned to upper.

If we hadn't added the value assigned to lower, the program would — in the case of lower = 5 and upper = 10 — generate a number between 1 and 6. We are simply ensuring that those 6 possibilities, as show above, are within the desired range of 5 to 10 (and not 1 to 6).

I was previously in the same situation as the other students when it came to trying to understand the calculation of

Math.floor(Math.random() * (upper - lower + 1)) + lower;

... however, I'm starting to understand it much better/quicker when going through my own thought process and methods of understanding the math portion and also thanks to staff and students like yourself in answering/providing helpful tips to us newbies!

My question here though is, if I'm getting this right, based on your explanation underneath Why + lower?, you mentioned that the example would generate a number from 5 to 10 --- couldn't the range be 5-11 when adding the lower to the end of the equation?

Example of when the Math.random() function generates a high 0.-something number since **1* is exclusive*:

Math.floor(Math.random() * (upper - lower + 1)) + lower;
//roundDownResultOf(0.9999999999 * (10 - 5 + 1)) + 5
                         // 0.9999999999 * 6 = 6; 6 + 5 = 11
                        // randomNum = 11
Steven Parker
Steven Parker
216,136 Points

That's not quite right. The actual steps would be:

  • .9999999999 * 6 = 5.9999999994
  • Math.floor(5.9999999994) = 5   (not 6)
  • 5 + 5 = 10
  • randomNum = 10

i gotcha homie simplist terms here tbh basically what is happening here is that Math is preety much like a calculator math.random is a function but you wont be able to add a value into cause it will only calculate numbers between .0 and 1 that is why we must mutplty it by other numbers to get what we need.

Math.floor(Math.random() * ((high - low)+1) + low);

math.floor is basically a rounding function where just like in real life instead of giving you decimal it will round in this down. if you use ceil it will go up.. ironic right... floor and ceiling = down and up hahahahaahahaha

mmm and then its just a big equation at the end thats all basically in the end saying to round down the number that is mutiplied with a random decimal and the high number giving by the low number given add by one and subtracted by the lower number.

the reason you add its just a way of validation, because there is a chance of getting a zero if you dont do the add one option and that'll just mess up your equation

mmmm hahaha hope you got some help? / knowledge?

Hazim Sami
Hazim Sami
10,185 Points

Thank you @stevenparker for explaining it so well!

ok thanks

W3Schools does a great job of explaining Math.random() and Math.floor(). See their examples here. Hope it helps.

https://www.w3schools.com/js/js_random.asp

I understand Steven Parker in his definition. But Neil Martin Orbase's question still remains unanswered... following this thread for an answer to his argument.

Steven Parker
Steven Parker
216,136 Points

Christian Fynbo may still want to chime in, but since you tagged me I feel compelled to point out that there is a flaw in one of the example assumptions. See the comment I added after Neil's.