0

So I am confused why we use Math.floor() for creating random numbers versus Math.round() or Math.ceil().

For example:

var enemyNumber = Math.floor(Math.random() * 4);

Why don't we use var enemyNumber = Math.ceil(Math.random() * 4); or var enemyNumber = Math.ceil(Math.random() * 4);

  • This is likely to be opinion-based, considering the fact that they are used differently for different purposes. – InSync Mar 28 '23 at 17:59
  • Note: The following shows an alternative way to produce random integers in JavaScript: https://stackoverflow.com/questions/6046918/how-to-generate-a-random-integer-in-the-range-0-n-from-a-stream-of-random-bits/62920514#62920514 – Peter O. Mar 28 '23 at 22:36
  • also see https://stackoverflow.com/a/1527820/1358308 for more explanation – Sam Mason Mar 29 '23 at 10:46

1 Answers1

2

The numbers from Math.random() are in the range 0 (inclusive) to 1 (exclusive). That means you might get a 0, but you'll never get 1.

Thus that formula starts off with multiplying by an integer, which in your example will give a value from 0 (inclusive) up to 4 (exclusive). If you want random integers like 0, 1, 2, and 3, you have to use .floor() to get rid of any fractional part entirely. In other words, you might get 3.999, and you don't want a 4, so .floor() throws away the .999 and you're left with 3.

Now this presumes that what you want is what most people want, a random integer between a minimum value and a maximum value. Once you understand what Math.random() returns, you're free to generate integers however you want.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • So, if I wanted the outputs to be 1, 2, 3 or 4, do I use `Math.ceil()`, `Math.round()`, or `Math.floor()` – coolcoder71012 Mar 28 '23 at 18:03
  • Yes, with your formula, using `Math.ceil()` would give you 1, 2, 3, or 4, while `Math.floor()` gives you 0, 1, 2, or 3. Using `Math.round()` would give you 0, 1, 2, 3, or 4, however I would be wary of that without consulting a statistician because it's a little biased towards 0. Not much at all, but a little. If I wanted that range, I'd use `.floor()` and set the upper bound at 5. – Pointy Mar 28 '23 at 18:19
  • 1
    @Pointy Rounding would give half as much probability for the two end-values of the range than for all of the other integers, unless you extended the range by 1/2 on each side. Easier to just use floor. – pjs Mar 28 '23 at 22:39
  • @pjs yea what I really meant was that I am not equipped to analyze that, and using the traditional `.floor()` would work without making my head hurt. – Pointy Mar 28 '23 at 23:26
  • with `ceil` there's a **very** small probability of getting 0 (2**-53 with common implementations) – Sam Mason Mar 29 '23 at 09:01