Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

generating a random number between min and max (inclusive) using JavaScript

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));

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading