-1

I have this following javascript code

var rnumber=Math.floor(Math.random()*50)+1;

now my doubt is why are they adding one is it to exclude 0 or to include 50 while finding the random number. Please provide me with the correct answer with an explanation.

  • 1
    https://developer.mozilla.org/en-US/docs/web/javascript/reference/global_objects/math/random <-- read the description – epascarello Jan 27 '20 at 21:13
  • 3
    "*is it to exclude 0 or to include 50*" - both. – Bergi Jan 27 '20 at 21:15
  • Does this answer your question? [Generating random whole numbers in JavaScript in a specific range?](https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range) – Ibu Jan 27 '20 at 21:21

4 Answers4

1

The Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1)

This definition means that if you multiply the random() by 50, as you did, you will get a maximum of 49.9. To enable getting the number 50 as well (while avoiding receiving the 0), you will need to add 1.

Nave Sade
  • 441
  • 2
  • 6
1

Let's see what each step does in Math.floor(Math.random()*50)+1;:

  • Math.random() returns a number between 0 and 1 (not including 1)
  • * 50 multiplies that number by 50, so now we're in the range between 0 and 50 (50 not included)
  • Math.floor() converts that number (float) into an integer by rounding down, the range is now between 0 and 49 (49 included)
  • + 1 changes the range to between 1 and 50

You were right.

Shomz
  • 37,421
  • 4
  • 57
  • 85
0

It does the same thing on both ends. You will always add 1. Suppose the number is 0 (lowest possible output) then you + 1. You now have 1 and you will never get 0 because if it's 0 you're always going to add one and get 1. --> 1 is the lowest possible output. You will never get 1 with Math.random. 49 is the highest possible output. Every time you get the highest number, 49, you + 1 and get 50. --> 50 becomes the highest possible output.

anna
  • 187
  • 1
  • 8
0

Math.random()'s range is essentially 0 to 0.99999999999999 repeating.

0 times 50 is 0. That rounded down is still 0. Then plus 1 is 1, making 1 the minimum result.

0.99999999999999 times 50 is 49.99999999999999. That rounded down is 49. Then plus 1 is 1, making 50 the maximum result.

That being said, if you want a simpler and more readable solution, I recommend randojs. You can use it like this:

console.log( rando(1, 50) );
<script src="https://randojs.com/1.0.0.js"></script>
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15