0 points
Submitted by Shivam Arora
about 9 years

How to get a random number between X(any number) and X(another number)?

We’ve been taught how to get a random number between 1 and any other number.

But what if we want to generate a random number between 2 and 10 or 5 and 10 etc.

Answer 519e8191678c20d59f000bf1

3 votes

Permalink

Keeping in mind that Math.random() generates numbers between 0 and 1. By default, 0 would be the start value and 1 would be the end value.

So, if x = start and y = end, you would do the following:

  • add x so the starting point changes from the default 0 to x
  • multiply by y-x so the ending point changes from the default 1 to y
  • when using Math.floor(), remember to +1 to y-x to accomodate the rounding downward to its nearest integer.

Formula:

Math.floor(Math.random() * ((y-x)+1) + x);

Example 1: a whole number between 2 and 10 would be:

// x = 2, y = 10
Math.floor(Math.random() * ((10-2)+1) + 2);
Math.floor(Math.random() * 9 + 2);

Example 2: a whole number between 5 and 10 would be:

// x = 5, y = 10
Math.floor(Math.random() * ((10-5)+1) + 5);
Math.floor(Math.random() * 6 + 5);

Example 3: a whole number between -2 and -10 would be:

// x = -2, y = -10
// note: no need to +1 since Math.floor() rounds down
Math.floor(Math.random() * (-10-(-2)) + (-2));
Math.floor(Math.random() * -8 - 2);
points
almost 9 years

2 comments

Shivam Arora almost 9 years

Thanxx.. It helped alot. But can you please explain reason behind (y-x) more for easy understanding?

Abdul almost 9 years

the (y-x) is to help in getting the number of figures withing the range. thats all.

Answer 5606c0c086f5526de00001dd

1 vote

Permalink

Please….I am a beginner programmer and don’t know how to do this. I need a script for a number between o and 0.33.

points
Submitted by Alina_Lee
over 6 years

1 comments

LiamGoodsell over 6 years

boop