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

Different equation but seems to work, I don't know why.

function mathRandom(number1, number2) { return Math.floor(Math.random() * (number1- number2)+ number2) + 1; } document.write(mathRandom(100,99));

using different numbers it seems to work, but using this example of number1 = 100 number2 = 99 (100- 99) + 99) +1 1+99 +1 =101 and since Math.random can produce a value of 0 but not including 1 and math floor rounds it down it will produce a value of 100, which in that aspect I get. However, I do not get in which part of this code it considers the lower number for the range, wouldn't it just go from 0 to 101

  • number1 = 100
  • number2 = 99
  • from your equation: Math.floor(Math.random() * (number1- number2)+ number2) + 1;
  • lets say: var sj = Math.random() * (100-99) + 99
  • therefore: sj = Math.random() * 100
  • Math.floor(sj) + 1;
  • therefore this is what you have: Math.floor(Math.random() * 100) + 1
  • remember the +1 make your random number to start from one and not zero anymore

1 Answer

Steven Parker
Steven Parker
243,200 Points

That formula is a little off, the classic formula for random numbers in a range is:

Math.floor(Math.random() * (number1 - number2 + 1)) + number2

where "number1" is the largest number in the range, and "number2" is the smallest.

Supplying 100 and 99 as the numbers will yield either a 99 or 100 every time, as expected.