How do you get a random number between two numbers in javascript?

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);

If you want to find a random integer in between min (inclusive) to max (inclusive), you can use the following formula:

Math.floor(Math.random() * (max - min + 1)) + min

Example: Integer Value Between Two Numbers

// input from the user
const min = parseInt(prompt("Enter a min value: "));
const max = parseInt(prompt("Enter a max value: "));

// generating a random number
const a = Math.floor(Math.random() * (max - min + 1)) + min;

// display a random number
console.log(`Random value between ${min} and ${max} is ${a}`);

Output

Enter a min value: 1
Enter a min value: 50
Random value between 1 and 50 is 47

In JavaScript, you can generate a random number with the Math.random() function.

Math.random() returns a random floating-point number ranging from 0 to less than 1 (inclusive of 0 and exclusive of 1)

The above program will show an integer output between min (inclusive) to max (inclusive).

First, the minimum and maximum values are taken as input from the user. Then the Math.random() method is used to get the random number from the passed value.

The Math.floor() returns the nearest integer value.

The Math.random() function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

Try it

Note: 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.

Syntax

Return value

A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

Examples

Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random() itself) aren't exact. If extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to reach the usually-excluded upper bound.

Getting a random number between 0 (inclusive) and 1 (exclusive)

function getRandom() {
  return Math.random();
}

Getting a random number between two values

This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max.

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

Getting a random integer between two values

This example returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn't an integer), and is less than (but not equal to) max.

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive
}

Note: It might be tempting to use Math.round() to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs.

Getting a random integer between two values, inclusive

While the getRandomInt() function above is inclusive at the minimum, it's exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The getRandomIntInclusive() function below accomplishes that.

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1) + min); // The maximum is inclusive and the minimum is inclusive
}

Specifications

Specification
ECMAScript Language Specification
# sec-math.random

Browser compatibility

BCD tables only load in the browser

See also

How do you generate a random number between two numbers in JavaScript?

random() * (max-min) + min); Generate a random integer between two numbers min and max (both min and max are inclusive).

How do you find the random value of two numbers?

Direct link to this answer.
The second example for rand() says this:.
"In general, you can generate N random numbers in the interval (a,b) with the formula r = a + (b-a). *rand(N,1).".
With a=20 and b=150, you get what you want..

How do you generate random numbers between ranges?

Generate a random number with a Max limit.
function generateRandom(maxLimit = 100){.
let rand = Math. random() * maxLimit;.
console. log(rand); // say 99.81321410836433..
rand = Math. floor(rand); // 99..
return rand;.

How do you generate a random number between two integers in Java?

Method 1: Using random class.
Import the class java.util.Random..
Make the instance of the class Random, i.e., Random rand = new Random().
Invoke one of the following methods of rand object: nextInt(upperbound) generates random numbers in the range 0 to upperbound-1 . nextFloat() generates a float between 0.0 and 1.0..