How Does Math.floor( (math.random() * 10) + 1 ); Work?
Solution 1:
Math.random()
provides a random number
from [0
,1
) (floating point: '[' = inclusive, ')' = exclusive).
So in Math.floor( (Math.random() * 10) + 1);
multiplying Math.random()
by 10
will provide a random number from [0
, 10
).
The +1
after the multiplication will change the output to be [1
, 11
).
Then finally Math.floor( ... )
converts the random number that is in the range from [1
, 11
) to an integer value.
So the range of the executed statement will be all integers from [1
, 10
]. Or to be more specific it will be one of the numbers in this set: { 1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
, 9
, 10
}
Solution 2:
As it is stated in MDN
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), 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.
That being said the minimum value of Math.random()*10
is 0 while the upper exclusive bound is 10. Adding one to this expression result in a number in the range [1,11). Then by taking the Math.floor we take an integer number in range [0,10], since Math.floor()
returns the largest integer less than or equal to a given number.
Solution 3:
Math.random method return a random number between 0 (inclusive) and 1 (exclusive). Which gives 0.9 * 10 = 9.
Solution 4:
By Google V8 Project:
Math.random() 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.
Math.random use an algorithm called xorshift128+
Read More about There's Math.random(), and then there's Math.random()
Post a Comment for "How Does Math.floor( (math.random() * 10) + 1 ); Work?"