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?

apsillers
  • 112,806
  • 17
  • 235
  • 239
Aziz Al-ghannam
  • 309
  • 1
  • 3
  • 13
  • @quixoto Because i saw this code many times, that's why i said "we", ill change it anyway> – Aziz Al-ghannam Nov 03 '11 at 22:44
  • 1
    I wasn't criticizing your wording. It's useful for this sort of question to actually state that it's something you see often, or see often in such-and-such kind of code, just so people have context and know how to best answer you. – Ben Zotto Nov 03 '11 at 22:52

7 Answers7

19

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).

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • is `Math.random()` really inclusive of `0`? i ran it in a `while` loop for 1m iterations and it did not generate `0` once :/ The reason I ask is because certain calculations like `Math.ceil(Math.random() * 10)` would be more succinct than `Math.floor(Math.random() * 10 + 1)` – oldboy Oct 18 '20 at 09:01
  • @oldboy Because javascript use double floating point numbers, it would seem that the probability of getting a particular value is about 1/2^53 ~ 1/10^16 . The probablity of getting a success in 1m trials is practically zero. See https://stackoverflow.com/questions/52048999/can-math-random-exactly-equal-5 and https://lemire.me/blog/2017/02/28/how-many-floating-point-numbers-are-in-the-interval-01/ – leonbloy Apr 03 '22 at 15:03
17

Why would anybody call Math.floor on a Math.random result?

In a nutshell, one calls Math.floor() when you want to truncate a decimal value to its nearest integer (by just dropping the decimal portion. So, 3.9 becomes 3, 2.1 becomes 2, etc... So, you would typically use that when you need an integer and you want the integer that is smaller than or equal to the decimal value. The math library also has Math.ceil() and Math.round(). Math.ceil() gets you the next larger integer, Math.round() rounds to the nearest integer going either up or down depending upon which is closer.

I've seen it used like: Math.floor(Math.random() * num);

Breaking Math.floor(Math.Random() * num) down into it's individual pieces and explaining each piece, you get this:

Math.random() gives you a random decimal number between 0 and 1, including 0, but not including 1. So, it might give you something like 0.38548569372.

Math.random() * num gives you a random decimal number between 0 and num, including 0, but not including num. So, if num was 10, it might give you 3.8548569372.

Math.floor(Math.random() * num)) gives you a random integer number between 0 and num, including 0, but not including num. So, it might give you 3.

Math.floor() truncates the decimal number to only the integer portion. A random integer is often used for getting a random value from an array (which needs to be an integer).

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Sorry to hi-jack, but to clarify... does floor round down, while ceiling rounds up? – Myles Dec 18 '13 at 16:36
  • 1
    @Myles - `Math.floor()` gives you the next lower integer. `Math.ceil()` gives you the next higher integer. `Math.round()` examines the value and gives you the next lower or next higher integer depending upon which it is closer to. In the future, the [MDN site](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor) is an excellent reference for all these types of questions. – jfriend00 Dec 18 '13 at 17:00
2

It's used to get an integer random number between 0 and (max - 1).

On the other hand it's faster to use | 0 as in

const randomInt = Math.random() * num | 0;

The | 0 is a binary or of 0 which the JavaScript spec effectively says the result is converted to an integer before the | happens. Note that | 0 is not the same as Math.floor. | 0 rounds to 0 whereas Math.floor rounds down.

         | 0   Math.floor         
------+------+------------
  2.5 |   2  |   2
  1.5 |   1  |   1
  0.5 |   0  |   0
 -0.5 |   0  |  -1
 -1.5 |  -1  |  -2
 -2.5 |  -2  |  -3
gman
  • 100,619
  • 31
  • 269
  • 393
  • for me bitwise operators feel like the javascript equivalent of the darknet, you definitely need to be able to see the matrix green text to be able to know how, when, and where to use these things – eballeste Dec 06 '22 at 17:13
  • I don't see it as the darknet. I see it as learning the language you're using. Every langauge has its idioms. People use `value = maybeValue || defaultValue` all over the place as well as `value = condition && expression` both of which look like voodoo but you get used to it. `| 0` is similar. You just need to look up what it means and now it's part of your knowledge. – gman Dec 06 '22 at 19:47
  • nevermind, i was speaking in metaphorical terms, at least to me, bit wise operators and how they work, and how people use them has always been hard to grasp, i still don't understand it... – eballeste Dec 08 '22 at 17:28
2

Math.random() will give you a long, random decimal. What one usually does is multiply that decimal by 10, 100, 1000, etc to get a random whole number. However, since such decimal is so long, to get a absolute whole number, you use Math.floor() to round that number down.

JCOC611
  • 19,111
  • 14
  • 69
  • 90
2

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 :)

Freesnöw
  • 30,619
  • 30
  • 89
  • 138
1
var num = Math.floor(Math.random() * 1000); // e.g. 885

var flNum = Math.random() * 1000; //e.g. 885.9936205333221

Try Math.random() * 1000 for example, you may get something like this: 885.9936205333221, in many cases we need a rounded number, so many developers use it with Math.floor or Math.ceil to get an integer like 885, if in your case, you don't mind having a float number, leave it as it's...

For more info about how Math.floor working, check this link:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

Alireza
  • 100,211
  • 27
  • 269
  • 172
1

Math.random() returns something like 0.8747230430599302 between [0,1)

We use .floor to round it down to the nearest integer. For example:

Math.random()*5 == 2.5889716914389282 This generates a number between [0,5).

Math.floor(Math.random()*5) == 2 //in this scenario Generates a number between [0,4]

switz
  • 24,384
  • 25
  • 76
  • 101
  • is `Math.random()` really inclusive of `0`? i ran it in a `while` loop for 1m iterations and it did not generate `0` once :/ The reason I ask is because certain calculations like `Math.ceil(Math.random() * 10)` would be more succinct than `Math.floor(Math.random() * 10 + 1)` – oldboy Oct 18 '20 at 09:02