Explanation of Code: Dealing with min and max - Javascript [duplicate] - javascript

This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(39 answers)
Closed 6 years ago.
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) +myMin;
}
I need a refresher on what the return statement is doing. I understand it creates a range for instance, 5 - 15. But I don't get why I'm subtracting the max from the min and adding + 1 and then +myMin.

But I don't get why im subtracting the max from the min and adding + 1 and then +myMin.
First remember that Math.random() returns a value in the range of [0, 1).
Lets start from the end:
+ myMin is done to ensure that the result is larger or equal to myMin.
Lets assume Math.random() returns 0. Then Math.floor(...) returns 0. If we didn't + myMin, return result would be 0 instead of myMin.
+ 1 is done to get random values that include myMax. Remember that Math.random() never returns 1, only values close to 1. I.e. the Math.floor(Math.random() * myMax) can never be myMax unless we add 1.
myMax - myMin is done because we do + myMin above. We have to account for increasing the result by myMin.
Lets assume Math.random() returns 0.5 and our range is 100 - 120. Without - myMin, we would get
Math.floor(0.5 * 120) + 100 = 60 + 100 = 160
That's clearly larger than 120. If we include - myMin:
Math.floor(0.5 * (120 - 100)) + 100 = (0.5 * 20) + 100 = 110
we get 110 which is exactly in the middle of our range (which makes sense intuitively since we get 0.5 as a random value).

Math.random returns float number between 0 to 1. For example if you take 1 to 10 range. Then Math.random will return minimum 0 and maximum 1 then you multiply it with 10-1=9. And you get 0 to 9. But when you add the minimum it will be increased to 1 to 10.

Correction - it's not creating a range, it is generating a random Integer number between a given range of numbers ( minimum and maximum number).
E.g. (5, 15) = (min, max)
Will result in a number that is in between this range.
Code explanation :
Math.floor(Math.random() * (myMax - myMin + 1)) +myMin;
Let's assume both max and min are = 15
So the above will look like:
Math.floor(Math.random() * (15 - 15 + 1)) + 15;
Which is equal to = 15, since 0 <= Math.random() * (1) < 1 so the floor of this is 0.
If you don't add that 1, it will not be valid for this corner case.
You add minimum to make sure the value remains between min and max.

Related

Why my Math.random method is adding numbers from the range? [duplicate]

Is there a way to generate a random number in a specified range with JavaScript ?
For example: a specified range from 1 to 6 were the random number could be either 1, 2, 3, 4, 5, or 6.
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
const rndInt = randomIntFromInterval(1, 6)
console.log(rndInt)
What it does "extra" is it allows random intervals that do not start with 1.
So you can get a random number from 10 to 15 for example. Flexibility.
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)
Where:
1 is the start number
6 is the number of possible results (1 + start (6) - end (1))
Math.random()
Returns an integer random number between min (included) and max (included):
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Or any random number between min (included) and max (not included):
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
Useful examples (integers):
// 0 -> 10
Math.floor(Math.random() * 11);
// 1 -> 10
Math.floor(Math.random() * 10) + 1;
// 5 -> 20
Math.floor(Math.random() * 16) + 5;
// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;
** And always nice to be reminded (Mozilla):
Math.random() does not provide cryptographically secure random
numbers. Do not use them for anything related to security. Use the Web
Crypto API instead, and more precisely the
window.crypto.getRandomValues() method.
Other solutions:
(Math.random() * 6 | 0) + 1
~~(Math.random() * 6) + 1
Try online
TL;DR
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max - min + 1))
}
To get the random number
generateRandomInteger(-20, 20);
EXPLANATION BELOW
integer - A number which is not a fraction; a whole number
We need to get a random number , say X between min and max.
X, min and max are all integers
i.e
min <= X <= max
If we subtract min from the equation, this is equivalent to
0 <= (X - min) <= (max - min)
Now, lets multiply this with a random number r
which is
0 <= (X - min) * r <= (max - min) * r
Now, lets add back min to the equation
min <= min + (X - min) * r <= min + (max - min) * r
For, any given X, the above equation satisfies only when r has range of [0,1] For any other values of r the above equation is unsatisfied.
Learn more about ranges [x,y] or (x,y) here
Our next step is to find a function which always results in a value which has a range of [0,1]
Now, the range of r i.e [0,1] is very similar to Math.random() function in Javascript. Isn't it?
The Math.random() function returns a floating-point, pseudo-random
number in the range [0, 1); that is, from 0 (inclusive) up to but not
including 1 (exclusive)
Random Function using Math.random() 0 <= r < 1
Notice that in Math.random() left bound is inclusive and the right bound is exclusive. This means min + (max - min) * r will evaluate to having a range from [min, max)
To include our right bound i.e [min,max] we increase the right bound by 1 and floor the result.
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max - min + 1))
}
To get the random number
generateRandomInteger(-20, 20);
Or, in Underscore
_.random(min, max)
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;
jsfiddle: https://jsfiddle.net/cyGwf/477/
Random Integer: to get a random integer between min and max, use the following code
function getRandomInteger(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
Random Floating Point Number: to get a random floating point number between min and max, use the following code
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
Math is not my strong point, but I've been working on a project where I needed to generate a lot of random numbers between both positive and negative.
function randomBetween(min, max) {
if (min < 0) {
return min + Math.random() * (Math.abs(min)+max);
}else {
return min + Math.random() * max;
}
}
E.g
randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)
Of course, you can also add some validation to make sure you don't do this with anything other than numbers. Also make sure that min is always less than or equal to max.
Get a random integer between 0 and 400
let rand = Math.round(Math.random() * 400)
document.write(rand)
Get a random integer between 200 and 1500
let range = {min: 200, max: 1500}
let delta = range.max - range.min
const rand = Math.round(range.min + Math.random() * delta)
document.write(rand)
Using functions
function randBetween(min, max){
let delta = max - min
return Math.round(min + Math.random() * delta)
}
document.write(randBetween(10, 15));
// JavaScript ES6 arrow function
const randBetween = (min, max) => {
let delta = max - min
return Math.round(min + Math.random() * delta)
}
document.write(randBetween(10, 20))
I wrote more flexible function which can give you random number but not only integer.
function rand(min,max,interval)
{
if (typeof(interval)==='undefined') interval = 1;
var r = Math.floor(Math.random()*(max-min+interval)/interval);
return r*interval+min;
}
var a = rand(0,10); //can be 0, 1, 2 (...) 9, 10
var b = rand(4,6,0.1); //can be 4.0, 4.1, 4.2 (...) 5.9, 6.0
Fixed version.
ES6 / Arrow functions version based on Francis' code (i.e. the top answer):
const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
Example
Return a random number between 1 and 10:
Math.floor((Math.random() * 10) + 1);
The result could be:
3
Try yourself: here
--
or using lodash / undescore:
_.random(min, max)
Docs:
- lodash
- undescore
The top rated solution is not mathematically correct as same as comments under it -> Math.floor(Math.random() * 6) + 1.
Task: generate random number between 1 and 6.
Math.random() returns floating point number between 0 and 1 (like 0.344717274374 or 0.99341293123 for example), which we will use as a percentage, so Math.floor(Math.random() * 6) + 1 returns some percentage of 6 (max: 5, min: 0) and adds 1. The author got lucky that lower bound was 1., because percentage floor will "maximumly" return 5 which is less than 6 by 1, and that 1 will be added by lower bound 1.
The problems occurs when lower bound is greater than 1. For instance,
Task: generate random between 2 and 6.
(following author's logic)
Math.floor(Math.random() * 6) + 2, it is obviously seen that if we get 5 here -> Math.random() * 6 and then add 2, the outcome will be 7 which goes beyond the desired boundary of 6.
Another example,
Task: generate random between 10 and 12.
(following author's logic)
Math.floor(Math.random() * 12) + 10, (sorry for repeating) it is obvious that we are getting 0%-99% percent of number "12", which will go way beyond desired boundary of 12.
So, the correct logic is to take the difference between lower bound and upper bound add 1, and only then floor it (to substract 1, because Math.random() returns 0 - 0.99, so no way to get full upper bound, thats why we adding 1 to upper bound to get maximumly 99% of (upper bound + 1) and then we floor it to get rid of excess). Once we got the floored percentage of (difference + 1), we can add lower boundary to get the desired randomed number between 2 numbers.
The logic formula for that will be: Math.floor(Math.random() * ((up_boundary - low_boundary) + 1)) + 10.
P.s.: Even comments under the top-rated answer were incorrect, since people forgot to add 1 to the difference, meaning that they will never get the up boundary (yes it might be a case if they dont want to get it at all, but the requirenment was to include the upper boundary).
I was searching random number generator written in TypeScript and I have written this after reading all of the answers, hope It would work for TypeScript coders.
Rand(min: number, max: number): number {
return (Math.random() * (max - min + 1) | 0) + min;
}
Inspite of many answers and almost same result. I would like to add my answer and explain its working. Because it is important to understand its working rather than copy pasting one line code. Generating random numbers is nothing but simple maths.
CODE:
function getR(lower, upper) {
var percent = (Math.random() * 100);
// this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
//now you have a percentage, use it find out the number between your INTERVAL :upper-lower
var num = ((percent * (upper - lower) / 100));
//num will now have a number that falls in your INTERVAL simple maths
num += lower;
//add lower to make it fall in your INTERVAL
//but num is still in decimal
//use Math.floor>downward to its nearest integer you won't get upper value ever
//use Math.ceil>upward to its nearest integer upper value is possible
//Math.round>to its nearest integer 2.4>2 2.5>3 both lower and upper value possible
console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}
Math.random() is fast and suitable for many purposes, but it's not appropriate if you need cryptographically-secure values (it's not secure), or if you need integers from a completely uniform unbiased distribution (the multiplication approach used in others answers produces certain values slightly more often than others).
In such cases, we can use crypto.getRandomValues() to generate secure integers, and reject any generated values that we can't map uniformly into the target range. This will be slower, but it shouldn't be significant unless you're generating extremely large numbers of values.
To clarify the biased distribution concern, consider the case where we want to generate a value between 1 and 5, but we have a random number generator that produces values between 1 and 16 (a 4-bit value). We want to have the same number of generated values mapping to each output value, but 16 does not evenly divide by 5: it leaves a remainder of 1. So we need to reject 1 of the possible generated values, and only continue when we get one of the 15 lesser values that can be uniformly mapped into our target range. Our behaviour could look like this pseudocode:
Generate a 4-bit integer in the range 1-16.
If we generated 1, 6, or 11 then output 1.
If we generated 2, 7, or 12 then output 2.
If we generated 3, 8, or 13 then output 3.
If we generated 4, 9, or 14 then output 4.
If we generated 5, 10, or 15 then output 5.
If we generated 16 then reject it and try again.
The following code uses similar logic, but generates a 32-bit integer instead, because that's the largest common integer size that can be represented by JavaScript's standard number type. (This could be modified to use BigInts if you need a larger range.) Regardless of the chosen range, the fraction of generated values that are rejected will always be less than 0.5, so the expected number of rejections will always be less than 1.0 and usually close to 0.0; you don't need to worry about it looping forever.
const randomInteger = (min, max) => {
const range = max - min;
const maxGeneratedValue = 0xFFFFFFFF;
const possibleResultValues = range + 1;
const possibleGeneratedValues = maxGeneratedValue + 1;
const remainder = possibleGeneratedValues % possibleResultValues;
const maxUnbiased = maxGeneratedValue - remainder;
if (!Number.isInteger(min) || !Number.isInteger(max) ||
max > Number.MAX_SAFE_INTEGER || min < Number.MIN_SAFE_INTEGER) {
throw new Error('Arguments must be safe integers.');
} else if (range > maxGeneratedValue) {
throw new Error(`Range of ${range} (from ${min} to ${max}) > ${maxGeneratedValue}.`);
} else if (max < min) {
throw new Error(`max (${max}) must be >= min (${min}).`);
} else if (min === max) {
return min;
}
let generated;
do {
generated = crypto.getRandomValues(new Uint32Array(1))[0];
} while (generated > maxUnbiased);
return min + (generated % possibleResultValues);
};
console.log(randomInteger(-8, 8)); // -2
console.log(randomInteger(0, 0)); // 0
console.log(randomInteger(0, 0xFFFFFFFF)); // 944450079
console.log(randomInteger(-1, 0xFFFFFFFF));
// Error: Range of 4294967296 covering -1 to 4294967295 is > 4294967295.
console.log(new Array(12).fill().map(n => randomInteger(8, 12)));
// [11, 8, 8, 11, 10, 8, 8, 12, 12, 12, 9, 9]
to return 1-6 like a dice basically,
return Math.round(Math.random() * 5 + 1);
Adding float with fixed precision version based on the int version in #Francisc's answer:
function randomFloatFromInterval (min, max, fractionDigits) {
const fractionMultiplier = Math.pow(10, fractionDigits)
return Math.round(
(Math.random() * (max - min) + min) * fractionMultiplier,
) / fractionMultiplier
}
so:
randomFloatFromInterval(1,3,4) // => 2.2679, 1.509, 1.8863, 2.9741, ...
and for int answer
randomFloatFromInterval(1,3,0) // => 1, 2, 3
Crypto-strong random integer number in range [a,b] (assumption: a < b )
let rand= (a,b)=> a+(b-a+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
console.log( rand(1,6) );
This function can generate a random integer number between (and including) min and max numbers:
function randomNumber(min, max) {
if (min > max) {
let temp = max;
max = min;
min = temp;
}
if (min <= 0) {
return Math.floor(Math.random() * (max + Math.abs(min) + 1)) + min;
} else {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
Example:
randomNumber(-2, 3); // can be -2, -1, 0, 1, 2 and 3
randomNumber(-5, -2); // can be -5, -4, -3 and -2
randomNumber(0, 4); // can be 0, 1, 2, 3 and 4
randomNumber(4, 0); // can be 0, 1, 2, 3 and 4
Using random function, which can be reused.
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomNum(1, 6);
This should work:
const getRandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
If the starting number is 1, as in your example (1-6), you can use Math.ceil() method instead of Math.floor().
Math.ceil(Math.random() * 6)
instead of
Math.floor(Math.random() * 6) + 1
Let's not forget other useful Math methods.
This is about nine years late, but randojs.com makes this a simple one-liner:
rando(1, 6)
You just need to add this to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.
<script src="https://randojs.com/1.0.0.js"></script>
Try using:
function random(min, max) {
return Math.round((Math.random() *( Math.abs(max - min))) + min);
}
console.log(random(1, 6));
Short Answer: It's achievable using a simple array.
you can alternate within array elements.
This solution works even if your values are not consecutive. Values don't even have to be a number.
let array = [1, 2, 3, 4, 5, 6];
const randomValue = array[Math.floor(Math.random() * array.length)];
This simple function is handy and works in ANY cases (fully tested).
Also, the distribution of the results has been fully tested and is 100% correct.
function randomInteger(pMin = 1, pMax = 1_000_000_000)
//Author: Axel Gauffre.
//Here: https://stackoverflow.com/a/74636954/5171000
//Inspired by: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_number_between_two_values
//
//This function RETURNS A RANDOM INTEGER between pMin (INCLUDED) and pMax (INCLUDED).
// - pMin and pMax should be integers.
// - HOWEVER, if pMin and/or pMax are FLOATS, they will be ROUNDED to the NEAREST integer.
// - NEGATIVE values ARE supported.
// - The ORDER of the 2 arguments has NO consequence: If pMin > pMax, then pMin and pMax will simply be SWAPPED.
// - If pMin is omitted, it will DEFAULT TO 1.
// - If pMax is omitted, it will DEFAULT TO 1 BILLION.
//
//This function works in ANY cases (fully tested).
//Also, the distribution of the results has been fully tested and is 100% correct.
{
pMin = Math.round(pMin);
pMax = Math.round(pMax);
if (pMax < pMin) { let t = pMin; pMin = pMax; pMax = t;}
return Math.floor(Math.random() * (pMax+1 - pMin) + pMin);
}
I discovered a great new way to do this using ES6 default parameters. It is very nifty since it allows either one argument or two arguments. Here it is:
function random(n, b = 0) {
return Math.random() * (b-n) + n;
}
This works for me and produces values like Python's random.randint standard library function:
function randint(min, max) {
return Math.round((Math.random() * Math.abs(max - min)) + min);
}
console.log("Random integer: " + randint(-5, 5));

How does Math.floor(Math.random() * (Max - Min + 1) + Min) work in JavaScript? (Theory)

I was learning JavaScript in freecodecamp.org, Basic JavaScript. In the stage 103/110 there was a task to create a function which takes 2 arguments (minimum value and maximum value) and the function should return a random number between them. The formula was given and I did the task and completed it, but I didn't quite understand why the formula works.
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
}
console.log(randomRange(10, 20))
This is the code.
and this is the formula Math.floor(Math.random()*(max - min + 1) + min.
Can you please explain the formula and why does this work?
I'll explain this formula:
Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
Say we want a random number from 5-15 (including both 5 and 15 as possible results). Well, we're going to have to work with Math.random(), which only produces values from 0 through approximately 0.99999999999999, so we need to do two tricks to be able to work with this.
The first trick is recognizing that Math.random()'s lowest possible return value is 0, and 0 times anything is 0, so we need to start our range at 0 and adjust to account for this at the end. Instead of calculating 5-15 from the beginning, we recognize that there are 11 values in 5-15 (5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15) and count up that many from 0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) to use 0-10 as our range instead. This is what the myMax - myMin part of the formula does. It defines our new max as 10. Then, at the end of the calculations, we'll just add 5 back to whatever result we get to make the possible result range change from 0-10 to 5-15. This is what the + myMin part of the formula does.
The second trick is recognizing that multiplying Math.random() by our new max range of 10 can only give us a result as high as about 9.999999999999 because Math.random() only goes as high as about 0.99999999999 (never actually 1). When we Math.floor() that later to make it an integer, it brings the result down to 9, so we need to add 1 there to make the maximum possible value 10 instead of 9. That's what the + 1 part of the formula does.
Let's finish this off by walking through an example.
Math.random() can be 0 at lowest and approximately 0.99999999999999 at highest (never 1). Let's just look at what happens with those two cases to see how the range works out.
If we run the case where we've called randomRange(5, 15) and Math.random() gives us 0, here's what we end up with:
Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
=
Math.floor(0 * (15 - 5 + 1) + 5);
=
Math.floor(0 * 11 + 5);
=
Math.floor(0 + 5);
=
Math.floor(5);
=
5
So the lowest value possible is 5. If we run the case where we've called randomRange(5, 15) and Math.random() gives us 0.99999999999999, here's what we end up with:
Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
=
Math.floor(0.99999999999999 * (15 - 5 + 1) + 5);
=
Math.floor(0.99999999999999 * 11 + 5);
=
Math.floor(10.9999999999999 + 5);
=
Math.floor(15.9999999999999);
=
15
So the highest value possible is 15.
Step by step:
Math.random() returns a floating point number in the range [0, 1), i.e. 0 is a possible outcome, but 1 isn't.
(myMax - myMin + 1) is an integer that represents the number of possible distinct integers you can get as final result.
Math.floor(Math.random() * (myMax - myMin + 1) is therefore a floating point in the range [0, myMax - myMin + 1)
By adding myMin to that, you get a floating point in the range [myMin, myMax + 1)
Finally, by applying Math.floor(), the possible values are restricted to integers in the range [myMin, myMax + 1), which for integers is equivalent to {myMin...myMax}.
Math.random() returns a floating point number in the range [0, 0.999999]
*(myMax - myMin + 1) returns the integer value
As an example if your random range is randomRange(10, 20),(myMax - myMin + 1) returns the integer value(20-10+1),that means 11.
There are 11 possible integers as (10,11,12,13,14,15,16,17,18,19,20)
*Math.floor(Math.random() * (myMax - myMin + 1)returns the floating point in the range of (0,myMax-myMin+1)
(0.99999999999999 * (20 - 10 + 1))=10.99999999999
*Therefore we add myMin to get the floating point numbers in the range of(myMin,myMax+1)
(0.99999999999999 * (20 - 10 + 1)+10)=20.99999999999
*Finally, by applying Math.floor() rounds the number DOWN to the nearest integer as 20

I'm trying to use random function in Javascript?

var x = 1 + Math.Random() % 9;
if (x==1)
// do something
else if (x==2)
// do something else
I used this line — (1 + Math.Random() % 9) — in C++ to get a number between 1 and 9, but in JavaScript I'm getting a different result.
Math.random() returns a value between 0 and 1, so instead using the modulo operator you need to use a multiplication.
1 + (Math.random() * 9);
Finally, you should round or .floor() that value
var x = Math.floor( 1 + ( Math.random() * 9 ) );
or, shorter
var x = ~~( 1 + ( Math.random() * 9 ) );
There is no Math.Random() function in JavaScript. It's Math.random(). Note the capitalization.
To get a random number between a certain minimum and maximum value, do this:
var min = 1, max = 9;
Math.floor(Math.random() * (max - min + 1)) + min;
Further reading: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random
In Javascript the Math.random function returns a number between 0 and 1. If you want to get a number between 1 and 9 you'll have to work with it a bit.
var number = ((Math.random() * 10) | 0) % 9 + 1
This will give you a result between 0 and 9
Math.floor(Math.random()*9)
And by the way, jQuery is a javascript framework. Math is a native javascript function

Need an explanation of this javascript

I have a question about this script I found and used. It works but I don't get why. The exercise was to make a list with random numbers from -50 to 50. The function below uses Math.floor(Math.random() * (the part i dont understand).
If I put this calculation on google I got as answer 151 and Math.random()*151 does not do from -50 to 50.
Can someone give me a clear explanation about this function below because I am sure that I am missing something.
this script works but I only want a clear explanation how
for (i = 0; i <= 100; i++)
{
Rnumber[i] = randomFromTo(-50,50);
}
function randomFromTo(from, to)
{
return Math.floor(Math.random() * (to - from + 1) + from);
}
to - from + 1 = 50 - (-50) + 1 = 101
Math.random() * 101 = number in range [0,101[
Math.floor([0,101[) = integer in range [0,100]
[0,100] + from = [0,100] + (-50) = integer in range [-50,50]
Which is exactly what is asked for.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random
Math.random returns a floating-point, pseudo-random number in the
range [0, 1) that is, from 0 (inclusive) up to but not including 1
(exclusive), which you can then scale to your desired range.
which when multiplied with a number > 1 and floored gives you an integer
Math.random() - get only value between 0 and 1.
Math.floor( number ) get integer down rounded value from number.
You should:
function randomFromTo(from, to)
{
// you can use doubled bitwise NOT operator which also as Math.floor get integer value from number but is much faster.
// ~1 == -2 , ~-2 == 1 and ~1.5 == -2 :)
return ~~( --from + ( Math.random() * ( ++to - from )) )
}

Generate random number between two numbers in JavaScript

Is there a way to generate a random number in a specified range with JavaScript ?
For example: a specified range from 1 to 6 were the random number could be either 1, 2, 3, 4, 5, or 6.
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
const rndInt = randomIntFromInterval(1, 6)
console.log(rndInt)
What it does "extra" is it allows random intervals that do not start with 1.
So you can get a random number from 10 to 15 for example. Flexibility.
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)
Where:
1 is the start number
6 is the number of possible results (1 + start (6) - end (1))
Math.random()
Returns an integer random number between min (included) and max (included):
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Or any random number between min (included) and max (not included):
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
Useful examples (integers):
// 0 -> 10
Math.floor(Math.random() * 11);
// 1 -> 10
Math.floor(Math.random() * 10) + 1;
// 5 -> 20
Math.floor(Math.random() * 16) + 5;
// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;
** And always nice to be reminded (Mozilla):
Math.random() does not provide cryptographically secure random
numbers. Do not use them for anything related to security. Use the Web
Crypto API instead, and more precisely the
window.crypto.getRandomValues() method.
Other solutions:
(Math.random() * 6 | 0) + 1
~~(Math.random() * 6) + 1
Try online
TL;DR
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max - min + 1))
}
To get the random number
generateRandomInteger(-20, 20);
EXPLANATION BELOW
integer - A number which is not a fraction; a whole number
We need to get a random number , say X between min and max.
X, min and max are all integers
i.e
min <= X <= max
If we subtract min from the equation, this is equivalent to
0 <= (X - min) <= (max - min)
Now, lets multiply this with a random number r
which is
0 <= (X - min) * r <= (max - min) * r
Now, lets add back min to the equation
min <= min + (X - min) * r <= min + (max - min) * r
For, any given X, the above equation satisfies only when r has range of [0,1] For any other values of r the above equation is unsatisfied.
Learn more about ranges [x,y] or (x,y) here
Our next step is to find a function which always results in a value which has a range of [0,1]
Now, the range of r i.e [0,1] is very similar to Math.random() function in Javascript. Isn't it?
The Math.random() function returns a floating-point, pseudo-random
number in the range [0, 1); that is, from 0 (inclusive) up to but not
including 1 (exclusive)
Random Function using Math.random() 0 <= r < 1
Notice that in Math.random() left bound is inclusive and the right bound is exclusive. This means min + (max - min) * r will evaluate to having a range from [min, max)
To include our right bound i.e [min,max] we increase the right bound by 1 and floor the result.
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max - min + 1))
}
To get the random number
generateRandomInteger(-20, 20);
Or, in Underscore
_.random(min, max)
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;
jsfiddle: https://jsfiddle.net/cyGwf/477/
Random Integer: to get a random integer between min and max, use the following code
function getRandomInteger(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
Random Floating Point Number: to get a random floating point number between min and max, use the following code
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
Math is not my strong point, but I've been working on a project where I needed to generate a lot of random numbers between both positive and negative.
function randomBetween(min, max) {
if (min < 0) {
return min + Math.random() * (Math.abs(min)+max);
}else {
return min + Math.random() * max;
}
}
E.g
randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)
Of course, you can also add some validation to make sure you don't do this with anything other than numbers. Also make sure that min is always less than or equal to max.
Get a random integer between 0 and 400
let rand = Math.round(Math.random() * 400)
document.write(rand)
Get a random integer between 200 and 1500
let range = {min: 200, max: 1500}
let delta = range.max - range.min
const rand = Math.round(range.min + Math.random() * delta)
document.write(rand)
Using functions
function randBetween(min, max){
let delta = max - min
return Math.round(min + Math.random() * delta)
}
document.write(randBetween(10, 15));
// JavaScript ES6 arrow function
const randBetween = (min, max) => {
let delta = max - min
return Math.round(min + Math.random() * delta)
}
document.write(randBetween(10, 20))
I wrote more flexible function which can give you random number but not only integer.
function rand(min,max,interval)
{
if (typeof(interval)==='undefined') interval = 1;
var r = Math.floor(Math.random()*(max-min+interval)/interval);
return r*interval+min;
}
var a = rand(0,10); //can be 0, 1, 2 (...) 9, 10
var b = rand(4,6,0.1); //can be 4.0, 4.1, 4.2 (...) 5.9, 6.0
Fixed version.
ES6 / Arrow functions version based on Francis' code (i.e. the top answer):
const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
Example
Return a random number between 1 and 10:
Math.floor((Math.random() * 10) + 1);
The result could be:
3
Try yourself: here
--
or using lodash / undescore:
_.random(min, max)
Docs:
- lodash
- undescore
The top rated solution is not mathematically correct as same as comments under it -> Math.floor(Math.random() * 6) + 1.
Task: generate random number between 1 and 6.
Math.random() returns floating point number between 0 and 1 (like 0.344717274374 or 0.99341293123 for example), which we will use as a percentage, so Math.floor(Math.random() * 6) + 1 returns some percentage of 6 (max: 5, min: 0) and adds 1. The author got lucky that lower bound was 1., because percentage floor will "maximumly" return 5 which is less than 6 by 1, and that 1 will be added by lower bound 1.
The problems occurs when lower bound is greater than 1. For instance,
Task: generate random between 2 and 6.
(following author's logic)
Math.floor(Math.random() * 6) + 2, it is obviously seen that if we get 5 here -> Math.random() * 6 and then add 2, the outcome will be 7 which goes beyond the desired boundary of 6.
Another example,
Task: generate random between 10 and 12.
(following author's logic)
Math.floor(Math.random() * 12) + 10, (sorry for repeating) it is obvious that we are getting 0%-99% percent of number "12", which will go way beyond desired boundary of 12.
So, the correct logic is to take the difference between lower bound and upper bound add 1, and only then floor it (to substract 1, because Math.random() returns 0 - 0.99, so no way to get full upper bound, thats why we adding 1 to upper bound to get maximumly 99% of (upper bound + 1) and then we floor it to get rid of excess). Once we got the floored percentage of (difference + 1), we can add lower boundary to get the desired randomed number between 2 numbers.
The logic formula for that will be: Math.floor(Math.random() * ((up_boundary - low_boundary) + 1)) + 10.
P.s.: Even comments under the top-rated answer were incorrect, since people forgot to add 1 to the difference, meaning that they will never get the up boundary (yes it might be a case if they dont want to get it at all, but the requirenment was to include the upper boundary).
I was searching random number generator written in TypeScript and I have written this after reading all of the answers, hope It would work for TypeScript coders.
Rand(min: number, max: number): number {
return (Math.random() * (max - min + 1) | 0) + min;
}
Inspite of many answers and almost same result. I would like to add my answer and explain its working. Because it is important to understand its working rather than copy pasting one line code. Generating random numbers is nothing but simple maths.
CODE:
function getR(lower, upper) {
var percent = (Math.random() * 100);
// this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
//now you have a percentage, use it find out the number between your INTERVAL :upper-lower
var num = ((percent * (upper - lower) / 100));
//num will now have a number that falls in your INTERVAL simple maths
num += lower;
//add lower to make it fall in your INTERVAL
//but num is still in decimal
//use Math.floor>downward to its nearest integer you won't get upper value ever
//use Math.ceil>upward to its nearest integer upper value is possible
//Math.round>to its nearest integer 2.4>2 2.5>3 both lower and upper value possible
console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}
Math.random() is fast and suitable for many purposes, but it's not appropriate if you need cryptographically-secure values (it's not secure), or if you need integers from a completely uniform unbiased distribution (the multiplication approach used in others answers produces certain values slightly more often than others).
In such cases, we can use crypto.getRandomValues() to generate secure integers, and reject any generated values that we can't map uniformly into the target range. This will be slower, but it shouldn't be significant unless you're generating extremely large numbers of values.
To clarify the biased distribution concern, consider the case where we want to generate a value between 1 and 5, but we have a random number generator that produces values between 1 and 16 (a 4-bit value). We want to have the same number of generated values mapping to each output value, but 16 does not evenly divide by 5: it leaves a remainder of 1. So we need to reject 1 of the possible generated values, and only continue when we get one of the 15 lesser values that can be uniformly mapped into our target range. Our behaviour could look like this pseudocode:
Generate a 4-bit integer in the range 1-16.
If we generated 1, 6, or 11 then output 1.
If we generated 2, 7, or 12 then output 2.
If we generated 3, 8, or 13 then output 3.
If we generated 4, 9, or 14 then output 4.
If we generated 5, 10, or 15 then output 5.
If we generated 16 then reject it and try again.
The following code uses similar logic, but generates a 32-bit integer instead, because that's the largest common integer size that can be represented by JavaScript's standard number type. (This could be modified to use BigInts if you need a larger range.) Regardless of the chosen range, the fraction of generated values that are rejected will always be less than 0.5, so the expected number of rejections will always be less than 1.0 and usually close to 0.0; you don't need to worry about it looping forever.
const randomInteger = (min, max) => {
const range = max - min;
const maxGeneratedValue = 0xFFFFFFFF;
const possibleResultValues = range + 1;
const possibleGeneratedValues = maxGeneratedValue + 1;
const remainder = possibleGeneratedValues % possibleResultValues;
const maxUnbiased = maxGeneratedValue - remainder;
if (!Number.isInteger(min) || !Number.isInteger(max) ||
max > Number.MAX_SAFE_INTEGER || min < Number.MIN_SAFE_INTEGER) {
throw new Error('Arguments must be safe integers.');
} else if (range > maxGeneratedValue) {
throw new Error(`Range of ${range} (from ${min} to ${max}) > ${maxGeneratedValue}.`);
} else if (max < min) {
throw new Error(`max (${max}) must be >= min (${min}).`);
} else if (min === max) {
return min;
}
let generated;
do {
generated = crypto.getRandomValues(new Uint32Array(1))[0];
} while (generated > maxUnbiased);
return min + (generated % possibleResultValues);
};
console.log(randomInteger(-8, 8)); // -2
console.log(randomInteger(0, 0)); // 0
console.log(randomInteger(0, 0xFFFFFFFF)); // 944450079
console.log(randomInteger(-1, 0xFFFFFFFF));
// Error: Range of 4294967296 covering -1 to 4294967295 is > 4294967295.
console.log(new Array(12).fill().map(n => randomInteger(8, 12)));
// [11, 8, 8, 11, 10, 8, 8, 12, 12, 12, 9, 9]
to return 1-6 like a dice basically,
return Math.round(Math.random() * 5 + 1);
Adding float with fixed precision version based on the int version in #Francisc's answer:
function randomFloatFromInterval (min, max, fractionDigits) {
const fractionMultiplier = Math.pow(10, fractionDigits)
return Math.round(
(Math.random() * (max - min) + min) * fractionMultiplier,
) / fractionMultiplier
}
so:
randomFloatFromInterval(1,3,4) // => 2.2679, 1.509, 1.8863, 2.9741, ...
and for int answer
randomFloatFromInterval(1,3,0) // => 1, 2, 3
Crypto-strong random integer number in range [a,b] (assumption: a < b )
let rand= (a,b)=> a+(b-a+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
console.log( rand(1,6) );
This function can generate a random integer number between (and including) min and max numbers:
function randomNumber(min, max) {
if (min > max) {
let temp = max;
max = min;
min = temp;
}
if (min <= 0) {
return Math.floor(Math.random() * (max + Math.abs(min) + 1)) + min;
} else {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
Example:
randomNumber(-2, 3); // can be -2, -1, 0, 1, 2 and 3
randomNumber(-5, -2); // can be -5, -4, -3 and -2
randomNumber(0, 4); // can be 0, 1, 2, 3 and 4
randomNumber(4, 0); // can be 0, 1, 2, 3 and 4
Using random function, which can be reused.
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomNum(1, 6);
This should work:
const getRandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
If the starting number is 1, as in your example (1-6), you can use Math.ceil() method instead of Math.floor().
Math.ceil(Math.random() * 6)
instead of
Math.floor(Math.random() * 6) + 1
Let's not forget other useful Math methods.
This is about nine years late, but randojs.com makes this a simple one-liner:
rando(1, 6)
You just need to add this to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.
<script src="https://randojs.com/1.0.0.js"></script>
Try using:
function random(min, max) {
return Math.round((Math.random() *( Math.abs(max - min))) + min);
}
console.log(random(1, 6));
Short Answer: It's achievable using a simple array.
you can alternate within array elements.
This solution works even if your values are not consecutive. Values don't even have to be a number.
let array = [1, 2, 3, 4, 5, 6];
const randomValue = array[Math.floor(Math.random() * array.length)];
This simple function is handy and works in ANY cases (fully tested).
Also, the distribution of the results has been fully tested and is 100% correct.
function randomInteger(pMin = 1, pMax = 1_000_000_000)
//Author: Axel Gauffre.
//Here: https://stackoverflow.com/a/74636954/5171000
//Inspired by: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_number_between_two_values
//
//This function RETURNS A RANDOM INTEGER between pMin (INCLUDED) and pMax (INCLUDED).
// - pMin and pMax should be integers.
// - HOWEVER, if pMin and/or pMax are FLOATS, they will be ROUNDED to the NEAREST integer.
// - NEGATIVE values ARE supported.
// - The ORDER of the 2 arguments has NO consequence: If pMin > pMax, then pMin and pMax will simply be SWAPPED.
// - If pMin is omitted, it will DEFAULT TO 1.
// - If pMax is omitted, it will DEFAULT TO 1 BILLION.
//
//This function works in ANY cases (fully tested).
//Also, the distribution of the results has been fully tested and is 100% correct.
{
pMin = Math.round(pMin);
pMax = Math.round(pMax);
if (pMax < pMin) { let t = pMin; pMin = pMax; pMax = t;}
return Math.floor(Math.random() * (pMax+1 - pMin) + pMin);
}
I discovered a great new way to do this using ES6 default parameters. It is very nifty since it allows either one argument or two arguments. Here it is:
function random(n, b = 0) {
return Math.random() * (b-n) + n;
}
This works for me and produces values like Python's random.randint standard library function:
function randint(min, max) {
return Math.round((Math.random() * Math.abs(max - min)) + min);
}
console.log("Random integer: " + randint(-5, 5));

Categories