re: How do you do random? VIEW POST

re: There is a subtle bug to consider with your code, though. If you want to guarantee an even spread among the numbers in the set of [0, 10], you'll h...

What about using Math.round() in place of Math.floor() in the original?


Also, try out the above link, you can make your own random functions to see if your hunches are correct. :)

I'm on my smartphone at the moment, but thanks. Your other response makes a lot of sense. That's something I hadn't thought about before.


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.

code of conduct - report abuse