Alex Rivera | Logout

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

Asked 2011-11-03T22:40:11.920
13

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?

Edit
Report

1 Answer

1

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

You combine them because otherwise it would return a float. Using Math.floor makes sure that it is a whole number inside of the range specified.

Math.random returns a flat in between 0 and 1. Multiplying it by your num or max range gets you a value with a max of that number (1 * num). So again, Math.floor is just forcing it to be a whole number.


Behind The Scenes:

RANDOM NUMBER -> .35 -> Multiplied by max (num) of 11 -> Gets 3.85 -> Math.floor(3.85) -> 3.


Keep in mind, num is the MAX + 1. Setting num to 5 will only generate numbers 1-4!


You can check out this link for more information: http://www.javascriptkit.com/javatutors/randomnum.shtml

Tada :)

answered 2011-11-03T22:43:28.820

Your Answer