Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I combine Math.floor with Math.random?

Why would anybody call Math.floor on a Math.random result? I've seen it used like:

Math.floor(Math.random() * num);

Can someone explain please?

like image 477
Aziz Al-ghannam Avatar asked Nov 03 '11 22:11

Aziz Al-ghannam


1 Answers

Math.random returns a floating-point number between 0 and 1.

Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

Multiplying this by n gives a floating point number between 0 (inclusive) and n (exclusive).

Math.floor is then used to convert this floating point number to an integer between 0 and n - 1 (inclusive).

like image 67
Mark Byers Avatar answered Sep 24 '22 15:09

Mark Byers