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?
The Math.random() function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range.
random will not return 1.0 itself, multiplying what Math. random returns with 100 will result in a max value of 99.999.... and when cast to an int turns to 99. Since the randomly generated number is supposed to include 100 you'll have to multiply with 101. Multiplying with 100 will result in a max int value of 99.
random generates a number between 0 and 1, that isn't a whole number, and also isn't 1. To get a number, for example between 0 and 10, multiply your answer by 10: Math. random() * 10 To get it to be a whole number, i.e. an integer, apply Math. floor, which rounds down to the nearest whole number: Math.
if(Math. random() < 0.5) IO. println("heads"); This fragment generates a random value between 0.0 and 1.0; if the random value is below 0.5, then it prints ``heads.
The 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With