DEV Community

Discussion on: How do you do random?

Collapse
 
krofdrakula profile image
Klemen Slavič

In that case, 0 and 10 would appear with about 50% the frequency of every other element.

If you imagine the number line after multiplying by 10, you'll understand what I mean:

0                    1                    2
|--------------------|--------------------|---....

<---------0---------><---------1---------><---....   Math.floor()
0---------><---------1---------><---------2---....   Math.round()
0<--------1----------><--------2----------><--....   Math.ceil()

This diagram shows you which floats map to which integer with different functions. As you can see, in the case of Math.round(), 0 has only half the length of every other number, so it would appear half as often. Same goes for 10 at the end of the interval:

9                    10
|--------------------|

9---------><--------10    Math.round()
<----------9--------->    Math.floor()

While 10 would appear in the resulting histogram, its frequency would be about half the frequency of every other non-zero integer.

FYI, Math.round() is just:

const round = n => Math.floor(n + 0.5);

You're effectively just shifting the mapping from floats to integers, but you're not making room for the max number. To have even distribution, you must have all intervals of equal length, and all the intervals covered by the scaled random number interval.