alex.mo.07
alex.mo.07

Reputation: 305

Concept of Math.floor(Math.random() * 5 + 1), what is the true range and why?

By multiplying the random number (which is between 0 and 1) by 5, we make it a random number between 0 and 5 (for example, 3.1841). Math.floor() rounds this number down to a whole number, and adding 1 at the end changes the range from between 0 and 4 to between 1 and 5 (up to and including 5).

The explanation above confused me... my interpretation below:

--adding the 5 gives it a range of 5 numbers --but it starts with 0 (like an array?) --so it's technically 0 - 4 --and by adding the one, you make it 1 - 5

I am very new to JS, don't even know if this kind of question is appropriate here, but this site has been great so far. Thank you for any help!

Upvotes: 6

Views: 9467

Answers (4)

James Donnelly
James Donnelly

Reputation: 128791

From the Mozilla Developer Networks' documentation on Math.random():

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

Here are two example randomly generated numbers:

Math.random() // 0.011153860716149211
Math.random() // 0.9729151880834252

Because of this, when we multiply our randomly generated number by another number, it will range from 0 to a maximum of 1 lower than the number being multiplied by (as Math.floor() simply removes the decimal places rather than rounding the number (that is to say, 0.999 becomes 0 when processed with Math.floor(), not 1)).

Math.floor(0.011153860716149211 * 5) // 0
Math.floor(0.9729151880834252 * 5)   // 4

Adding one simply offsets this to the value you're after:

Math.floor(0.011153860716149211 * 5) + 1 // 1
Math.floor(0.9729151880834252 * 5) + 1   // 5

Upvotes: 6

Paul S.
Paul S.

Reputation: 66334

15.8.2.14 Math.random from the ES5 spec,

Returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy. This function takes no arguments.

So,

x = Math.random(); // 0 ≤ x < 1
y = x * 5;         // 0 ≤ y < 5
z = y + 1;         // 1 ≤ z < 6
i = Math.floor(z); // 1 ≤ i ≤ 5, i ∈ ℤ, ℤ integers

Which means

i ∈ {1, 2, 3, 4, 5}

Upvotes: 0

Danilo Valente
Danilo Valente

Reputation: 11352

Note that:

  • 0 <= Math.random() **<** 1
  • Math.floor(x.yz) = x

And therefore, the number given is a integer in the interval:

x = Math.floor((0..0.999999999) * 5 + 1)
x = (0..4) + 1

Upvotes: 0

Zero Fiber
Zero Fiber

Reputation: 4465

Math.Random() returns a number between 0 and 1, excluding 1.

So when you multiply it with 5, you get a number between 0 and 5 but not 5.

Math.floor() on this number rounds down to a whole number.

So numbers you will get are either 0, 1, 2, 3 or 4.

Adding 1 to this range gives you a number in [1, 2, 3, 4, 5].

Upvotes: 2

Related Questions