Generate random number between two numbers in Java

2018-12-31 05:16发布

Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?

18条回答
旧人旧事旧时光
2楼-- · 2018-12-31 05:52

Instead of Math.random(), you can use crypto.getRandomValues() to generate evenly-distributed cryptographically-secure random numbers. Here's an example:

function randInt(min, max) {
  var MAX_UINT32 = 0xFFFFFFFF;
  var range = max - min;

  if (!(range <= MAX_UINT32)) {
    throw new Error(
      "Range of " + range + " covering " + min + " to " + max + " is > " +
      MAX_UINT32 + ".");
  } else if (min === max) {
    return min;
  } else if (!(max > min)) {
    throw new Error("max (" + max + ") must be >= min (" + min + ").");
  }

  // We need to cut off values greater than this to avoid bias in distribution
  // over the range.
  var maxUnbiased = MAX_UINT32 - ((MAX_UINT32 + 1) % (range + 1));

  var rand;
  do {
    rand = crypto.getRandomValues(new Uint32Array(1))[0];
  } while (rand > maxUnbiased);

  var offset = rand % (range + 1);
  return min + offset;
}

console.log(randInt(-8, 8));          // -2
console.log(randInt(0, 0));           // 0
console.log(randInt(0, 0xFFFFFFFF));  // 944450079
console.log(randInt(-1, 0xFFFFFFFF));
// Uncaught Error: Range of 4294967296 covering -1 to 4294967295 is > 4294967295.
console.log(new Array(24).fill().map(n => randInt(8, 12)));
// [11, 8, 8, 11, 10, 8, 8, 12, 12, 12, 9, 9,
//  11, 8, 11, 8, 8, 8, 11, 9, 10, 12, 9, 11]
console.log(randInt(10, 8));
// Uncaught Error: max (8) must be >= min (10).

查看更多
临风纵饮
3楼-- · 2018-12-31 05:57

Or, in Underscore

_.random(min, max)
查看更多
冷夜・残月
4楼-- · 2018-12-31 05:59
function random(min, max){
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
查看更多
残风、尘缘若梦
5楼-- · 2018-12-31 06:00
function randomIntFromInterval(min,max) // min and max included
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

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.

查看更多
孤独寂梦人
6楼-- · 2018-12-31 06:00

TL;DR

function generateRandomInteger(min, max) {
  return Math.floor(min + Math.random()*(max + 1 - min))
}

To get the random number generateRandomInteger(-20, 20);

EXPLANATION BELOW

We need to get a random integer, say X between min and max.

Right?

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

Now, lets chose a function which results in r such that it satisfies our equation range as [min,max]. This is only possible if 0<= r <=1

OK. Now, the range of r i.e [0,1] is very similar to Math.random() function result. 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)

For example,

Case r = 0

min + 0 * (max-min) = min

Case r = 1

min + 1 * (max-min) = max

Random Case using Math.random 0 <= r < 1

min + r * (max-min) = X, where X has range of min <= X < max

The above result X is a random numeric. However due to Math.random() our left bound is inclusive, and the right bound is exclusive. To include our right bound we increase the right bound by 1 and floor the result.

function generateRandomInteger(min, max) {
  return Math.floor(min + Math.random()*(max + 1 - min))
}

To get the random number

generateRandomInteger(-20, 20);

查看更多
牵手、夕阳
7楼-- · 2018-12-31 06:01

Sense you need to add 1 to the max number, and then subtract the minimum number for any of this to work, and I need to make a lot of random Integers, this function works.

var random = function(max, min) {
    high++;
    return Math.floor((Math.random()) * (max - min)) + min;
};

This works with both negative, and positive numbers, and I'm working on decimals for a library.

查看更多
登录 后发表回答