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 trialseong lee
4,503 Pointscan someone explain the equation
Can someone explain how the math equation works in the video
6 Answers
Steven Parker
231,275 PointsThis formula returns a random number within a range (inclusive): Math.floor(Math.random() * (upper - lower + 1)) + lower
.
The inner calculation returns the size of the range (upper - lower + 1).
Math.random() returns some value between 0 and 1, so when you multiply that by the size of the range you get some number between 0 and the size of the range.
Math.floor() returns only the integer part of that result.
Finally, adding the lower number moves the range up so that the number is between the upper and lower values originally requested.
Armand van Alphen
16,969 PointsTo add to the answer of Steven Parker Its is an example of the math that is taking place I hope it will help you.
Here is an example what can happen with the aguments 9 and 5 passed to it first the code that we will run ="Math.floor(Math.random() * (upper - lower + 1)) + lower."
function call to math.floor()
math.floor gets 1 argument which is the result of
(Math.random() * (upper - lower + 1))
math.random() is called which generates 0.5555.
the result of math.random gets multiplied by (upper - lower + 1)
upper - lower = 4;
result of 4 + 1 = 5;
5 get returned;
result of 5 * 0.5555 = 2,7775;
result is returned;
result of math.floor(2,7775) = 2;
2 gets returned;
2 + lower = 7; //lower = 5;
so the end result of this task = 7.
special thanks to steven parker that pointed out my mistake
Steven Parker
231,275 Pointsarmaniimus — You said the parameters were 9 and 5, but based on your math breakdown you were apparently going for a number between 1 and 5 (upper=5
and lower=1
).
If the parameters actually had been 9 and 5, 3 would not have been a possible result.
Armand van Alphen
16,969 PointsI edited my original answer thanks steven parker for pointing out my mistake.
seong lee
4,503 PointsWow thank you both of you guys I really appreciate both of your help!!!
Justin Farrar
7,780 PointsThis is Very Helpful !!!
Dianthe Velzen
1,443 PointsIncredibly helpful!!
Nick Evershed
6,429 PointsI still don't understand, can it be simpler?