This forum is now read-only. Please use our new forums! Go to forums
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
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);
Answer 5606c0c086f5526de00001dd
1 vote
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.
1 comments
LiamGoodsell over 8 years
boop
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency
2 comments
Thanxx.. It helped alot. But can you please explain reason behind (y-x) more for easy understanding?
the (y-x) is to help in getting the number of figures withing the range. thats all.