Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random numbers in specified range - various cases (int, float, inclusive, exclusive)

given a Math.random() function which returns a number between [0,1) and min max values to specify the range, how can we generate numbers for the following cases:

Case we want integer:

  • A: (min,max) ?
  • B: [min,max) return Math.floor(Math.random() * (max - min)) + min;
  • C: (min,max] ?
  • D: [min,max] return Math.floor(Math.random() * (max - min + 1)) + min;

Case we want float:

  • A: (min,max) ?
  • B: [min,max) return Math.random() * (max - min) + min;
  • C: (min,max] ?
  • D: [min,max] ?
like image 489
tgogos Avatar asked Oct 16 '15 09:10

tgogos


People also ask

How do you generate random numbers in a specific range in Python?

Use randrnage() to generate random integer within a range Use a random. randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random. randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).


1 Answers

Integers Your formula for B. is correct, everything else is obtained by trivial +1 -1 corrections:

  • A. (min, max) = [min + 1, max), therefore from B. we obtain min + 1 + Math.floor(Math.random() * (max - min - 1))
  • B. min + Math.floor(Math.random() * (max - min))
  • C. Since in the interval arithmetic (min, max] = max - [0, max - min), one could also write max - Math.floor(Math.random() * (max - min))
  • D. [min, max] = [min, max + 1), therefore: min + Math.floor(Math.random() * (max + 1 - min))

Floats. As V13 already pointed out, the question is somewhat ill-posed: if we consider single points as measure-zero sets, there is almost (in measure-theoretical sense) no difference between the four sets... However, if you want to guarantee that the excluded interval boundaries are never (not merely "almost never") sampled, and if you assume that there are no rounding errors, you could do something like this:

  • A: var middle = (min + max) / 2; var sign = Math.random() > 0.5 ? 1 : -1; return middle + sign * (max - min) / 2 * Math.random(); This solution puts a tiny little bit more mass on 0, but this should be negligible for all practical purposes.

  • B: min + Math.random() * (max - min), yes.

  • C: max - Math.random() * (max - min), symmetric to the above.
  • D: It is not possible to guarantee that we ever hit the upper interval boundary, so we can just use min + Math.random() * (max - min).

The difference between A and D is the following: if we tried to use the formula min + Math.random() * (max - min) in A, we might occasionally get a 0 (because the range of possible numbers is actually finite). However, no reasonable statistic could ever complain that the upper bound is not hit in D.

like image 56
Andrey Tyukin Avatar answered Sep 27 '22 21:09

Andrey Tyukin