skip to Main Content

I tried this function to find a random int number between two bonds, I know the method of Math.floor () and Math.random() how works, but I could not understand the logic with this function (max-min + 1) and the addition of min. why do we need to use (max-min+1) then the addition ofmin?

function random(min, max) {
    const num = Math.floor(Math.random() * (max - min + 1)) + min;
    return num;
}

console.log(random(5, 10));

2

Answers


  1. The purpose of (max - min + 1) is to determine the total number of possible values within the specified range, and it ensures that when you multiply it by Math.random(), you consider all the integers within that range. Adding 1 is crucial to include the upper bound of the range.

    For example, if you want to generate random numbers between 3 and 6 (inclusive). The range is 3, 4, 5, 6. If you only calculate (max - min), it would be (6 - 3), which equals 3. Without adding 1, you would have a range of 3 different values (3, 4, 5), and the upper bound (6) would be excluded.

    By adding 1 to the calculation (max - min), you get (6 – 3 + 1), which equals 4. Now, you have a range of 4 different values (3, 4, 5, 6), including the upper bound.

    Login or Signup to reply.
  2. Well this is something you don’t generally get at the beginning, so let’s break it down:

    1. The math.floor method runs down your floats to the nearest whole number e.g -0.98 will be -1 but 0.98 will be 0 and so on.
    2. The math.random method returns a random float that is less than 1 and greater than or equal to 0 (1 > x <= 0).
    3. The formula (max – min +1): this formula is to find the range of numbers you want, the added 1 is to include the last digit(upper bound) so to understand use BODMAS(addition before subtraction).
      Note: this calculation might be numbers less than your lower bound.
    4. The last min added is to ensure that the random number generate is within your lower and upper bound.

    Now let’s go through your code:
    The upper bound is 10
    The lower bound is 5
    Math.random generates a pseudo-float e.g 0.5

    >     First min = min + 1 (min = 5 + 1 = 6)
    >     Then max = max - min (max = 10 - 6 = 4)
    >     Now math.random = 0.5 
    >     0.5 * max (0.5 * 4 = 2)
    Math.floor(2) = 2
    
    2 + min (2 + 5 = 7)
    And 7 is returned
    

    Hope this give a better understanding of the problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search