Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Math.floor( (Math.random() * 10) + 1 ); work?

Tags:

javascript

I understand that Math.floor rounds the number to the lowest integer but when we do this: Math.random() * 10 wouldn't it multiply the number by 10 for example 9 * 10 = 90 so how would the number be between 1 and 10?

Thank you for helping I got the answer!

like image 751
Gulnoor Avatar asked Aug 17 '26 19:08

Gulnoor


2 Answers

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 }

like image 66
Patrick Barr Avatar answered Aug 19 '26 10:08

Patrick Barr


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.

like image 26
Christos Avatar answered Aug 19 '26 10:08

Christos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!