Answer the question
In order to leave comments, you need to log in
Newbie Question: Math.floor / Math.random?
I immediately apologize for the Lohovsky question.
I make playing "dice" according to the example in the textbook, the question appeared -
Here's how in the textbook:
var die = Math.floor(Math.random()*6 + 1);
Thus, the author claims that my result will always be between 1 and 6, inclusive.
But if Math.random( ) gives me numbers between 0 and 1, and then we multiply that number by 6 and add 1, then round up to the nearest integer—isn't there a small chance of getting the number 7?
Thanks
Answer the question
In order to leave comments, you need to log in
randomly generates in the range [0; 1), so 7 will never work there
Math.random() returns numbers from 0 to 1, not including 1, i.e. numbers in the range [0, 1), respectively, the range Math.floor(Math.random()*6 + 1) = [1, 7)
Therefore, after discarding the fractional part, a number from 1 to 6 will be obtained.
It seems that's why:
Math.random returns from 0 (inclusive) to 1 (not inclusive).
Source: javascript.ru/Math.random
Just yesterday I was looking for a translation of Float to Int in Java, just in one of the answers on StackOverflow you can see the difference between floor/truncate/round stackoverflow.com/questions/1295424/how-to-convert-float-to-int-with- java, and in addition to this description of random'a:
random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
i.e.
0.0 <= random() < 1.0
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question