T
T
The Whiz2012-07-16 16:11:40
Programming
The Whiz, 2012-07-16 16:11:40

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

5 answer(s)
L
LeoCcoder, 2012-07-16
@modernstyle

randomly generates in the range [0; 1), so 7 will never work there

I
ivnik, 2012-07-16
@ivnik

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.

F
freeek, 2012-07-16
@freeek

Math.floor rounds the number down :)

S
Salavat Sitdikov, 2012-07-16
@zona7o

It seems that's why:
Math.random returns from 0 (inclusive) to 1 (not inclusive).
Source: javascript.ru/Math.random

N
Nikita Permin, 2012-07-16
@NekitoSP

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 question

Ask a Question

731 491 924 answers to any question