Math.floor (Math.random ()) what does +1 actually do?

When you have Math.floor(Math.random()*10)+1 , it should select a random number from 1 to 10 from what I understand.

However, when I change +1 to any number higher or lower, then 1 will get the same result. Why is this? What does +1 mean?

+6
source share
4 answers

The random number generator produces a value in the range from 0.0 to n = 1.0. If you need a number from 1 to what you will need to apply an offset of +1 .

You can usually use:

 Math.floor(Math.random() * N) + M 

This will create values โ€‹โ€‹between M and M + N - 1.

demo script

+8
source

Math.random() generates a random number from 0 to 1.

Therefore, Math.random()*10 generates a random number from 0 to 10, and (Math.random()*10)+1 generates a number from 1 to 11.

Math.floor() divides the decimal of this number and makes it an integer from 0 to 10.

You can see the sequential progression of logic here

+3
source

The total number is from 1 to 10

  • Math.random () generates a number from 0 to 1 (with many decimals).

etc .: math.random () [randomly: 0.19157057767733932]
(this number will still have many decimal places)

To get a random integer, you need to multiply an arbitrary generated number by 10.

etc.
math.random () * 10 = [random return: 2.9757621488533914]

  • Since the number will still have many decimal places, use the floor () method to round the number down / the nearest integer, this will give ua between 0 and 9. Then u can add 1 to make it a number from 1 to 10.

etc.:
math.floor (0.6) [return 0]
math.floor (0,6) + 1 [return 1]

+2
source

The main ones:

(random() >= 0) always true

(random() < 1) always true

(Math.floor(random()) == 0) always true

Maximum:

(Math.floor(random() * 10) >= 0) always true

(Math.floor(random() * 10) < 10) always true

Minimum:

(Math.floor(random() * 10) + 1 >= 1) always true

(Math.floor(random() * 10) + 1 < 11) always true

Max. round:

(Math.round(random() * 10, 0) >= 0) always true

(Math.round(random() * 10, 0) <= 10) always true

0
source

Source: https://habr.com/ru/post/919135/


All Articles