Generating random whole numbers in JavaScript in a specific range
There are some examples on the Mozilla Developer Network page:
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Here's the logic behind it. It's a simple rule of three:
Math.random()
returns a Number
between 0 (inclusive) and 1 (exclusive). So we have an interval like this:
[0 .................................... 1)
Now, we'd like a number between min
(inclusive) and max
(exclusive):
[0 .................................... 1)
[min .................................. max)
We can use the Math.random
to get the correspondent in the [min, max) interval. But, first we should factor a little bit the problem by subtracting min
from the second interval:
[0 .................................... 1)
[min - min ............................ max - min)
This gives:
[0 .................................... 1)
[0 .................................... max - min)
We may now apply Math.random
and then calculate the correspondent. Let's choose a random number:
Math.random()
|
[0 .................................... 1)
[0 .................................... max - min)
|
x (what we need)
So, in order to find x
, we would do:
x = Math.random() * (max - min);
Don't forget to add min
back, so that we get a number in the [min, max) interval:
x = Math.random() * (max - min) + min;
That was the first function from MDN. The second one, returns an integer between min
and max
, both inclusive.
Now for getting integers, you could use round
, ceil
or floor
.
You could use Math.round(Math.random() * (max - min)) + min
, this however gives a non-even distribution. Both, min
and max
only have approximately half the chance to roll:
min...min+0.5...min+1...min+1.5 ... max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round()
min min+1 max
With max
excluded from the interval, it has an even less chance to roll than min
.
With Math.floor(Math.random() * (max - min +1)) + min
you have a perfectly even distribution.
min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval)
| | | | | |
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor()
min min+1 max-1 max
You can't use ceil()
and -1
in that equation because max
now had a slightly less chance to roll, but you can roll the (unwanted) min-1
result too.
Java Generate Random Number Between Two Given Values
You could use e.g. r.nextInt(101)
For a more generic "in between two numbers" use:
Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;
This gives you a random number in between 10 (inclusive) and 100 (exclusive)
Generate random integers between 0 and 9
Try random.randrange
:
from random import randrange
print(randrange(10))
How to generate a random int in C?
Note: Don't use
rand()
for security. If you need a cryptographically secure number, see this answer instead.
#include <time.h>
#include <stdlib.h>
srand(time(NULL)); // Initialization, should only be called once.
int r = rand(); // Returns a pseudo-random integer between 0 and RAND_MAX.
On Linux, you might prefer to use random and srandom.
Generate random number between two numbers in JavaScript
Important
The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:
const rndInt = Math.floor(Math.random() * 6) + 1
console.log(rndInt)
How to Generate a random number of fixed length using JavaScript?
console.log(Math.floor(100000 + Math.random() * 900000));
Generating a Random Number between 1 and 10 Java
As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.
Generally speaking, if you need to generate numbers from min
to max
(including both), you write
random.nextInt(max - min + 1) + min
Related Topics
Using a Database Table as a Queue
How to Execute a Native SQL Script in JPA/Hibernate
Removing Duplicate Rows (Based on Values from Multiple Columns) from SQL Table
How to Use a MySQL Database with an App Engine Application
Converting a String to Hex in SQL
How to Compare Dates in SQL Server
Create Postgresql Role (User) If It Doesn't Exist
Script Entire Database SQL-Server
Flattening of a 1 Row Table into a Key-Value Pair Table
How to Aggregate Over Rolling Time Window with Groups in Spark
Grant Privileges for a Particular Database in Postgresql
Oracle SQL: Update If Exists Else Insert
Suggestions for Implementing Audit Tables in SQL Server
MySQL Full Text Search with Partial Words
Generate Default Values in a Cte Upsert Using Postgresql 9.3
Error Trying to Call Stored Procedure with Prepared Statement
How to Report an Error from a SQL Server User-Defined Function