Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 375
Near Avatar asked Jun 27 '12 14:06

Near


People also ask

Is 1 Included in Math random?

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.

What does Math random () * 100 do?

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.

How does Math Floor Math random work?

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.

What does Math random () 0.5 do?

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.


2 Answers

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

like image 105
tadman Avatar answered Sep 18 '22 22:09

tadman


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

like image 34
jacktheripper Avatar answered Sep 21 '22 22:09

jacktheripper