When you have Math.floor(Math.random()*10)+1
its supposed to pick a random number between 1-10 from what I understand.
However, when I change the +1
to any number higher or lower then 1
I get the same result. Why is this? What does the +1
mean exactly?
When you have Math.floor(Math.random()*10)+1
its supposed to pick a random number between 1-10 from what I understand.
However, when I change the +1
to any number higher or lower then 1
I get the same result. Why is this? What does the +1
mean exactly?
4 Answers
Reset to default 9The random number generator produces a value in the range of 0.0 <= n < 1.0. If you want a number between 1 and something you'll need to apply a +1
offset.
Generally you can use:
Math.floor(Math.random() * N) + M
This will generate values between M and M + N - 1.
demo Fiddle
Math.random()
generates a random number between 0 and 1.
Therefore Math.random()*10
generates a random number between 0 and 10, and (Math.random()*10)+1
a number between 1 and 11.
Math.floor()
drops the decimal of this number, and makes it an integer from 0 to 10.
You can see a sequential progression of the logic here
Whole number is between 1 and 10
- Math.random() generates number between 0 and 1 (with many decimal places).
etc:
math.random() [randomly return : 0.19157057767733932]
(this number will still have many decimal places)
To get a random whole number, you need to multiply random generated number by 10.
etc
math.random()*10 =[randomly return : 2.9757621488533914]
- Since the number will still have many decimal places, use floor() method to round a number down/nearest integer, this will give u a value between 0 and 9. Then, u can add 1 to make it a number between 1 and 10.
etc:
math.floor(0.6) [return 0 ]
math.floor(0.6)+ 1 [return 1]
Basic:
(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
+1
and you still end up with numbers between 1-10 something is very wrong. – Dave Newton Commented Jun 27, 2012 at 14:101
does, but you have some other issue in your code. If you have such an issue, please post your actual code. – user1106925 Commented Jun 27, 2012 at 14:17