====== Javascript Random (function) number distribution ====== The Javascript Math.random is very useful for generating random numbers. However, is the number distribution even across the range? This is important because a lot of websites implement this for various random things, such as banner rotation, etc. While it is best to do some of this logic at the server, sometimes its just easier to do this at the client using Javascript. Anyway this is a small test to check the distribution out. I did this because I created a samll random jeopardy website and wanted to make sure all of the "answers" had an even distribution. To achieve this, I decided to use the command-line javascript as it is easier to do, without requiring a browser. So I installed spidermonkey for this. ===== Installing spidermonkey ===== See [[tech:javascript:spidermonkey]] ===== The script ===== Below is the script I wrote to test this. In this test I am generating random numbers between 1 and 320 a total of 100,000,000 times and counting their occurance. var dist = []; var rv; for (loopi = 1; loopi <= 320; loopi++) { dist[loopi]=0; } for (loopi = 0; loopi <= 100000000; loopi++) { rv=Math.floor(Math.random()*319)+1; //print(rv); dist[rv]=dist[rv]+1; } for (loopi = 1; loopi <= 320; loopi++) { print(loopi + " - " + dist[loopi]); } ===== Test ===== On running this very large sample set generation and distribution I found that the result was infact very evenly distributed. Here is the output to prove it. I thought of graphing it, but it is quite obvious just by observing the numbers that the distribution is quite even. 1 - 312999 2 - 313682 3 - 313696 4 - 313211 5 - 313773 6 - 313538 7 - 313230 8 - 314019 9 - 315107 10 - 313173 11 - 313186 12 - 312954 13 - 313650 14 - 313106 15 - 312534 16 - 313039 17 - 314425 18 - 311901 19 - 312643 20 - 313913 21 - 314109 22 - 312848 23 - 313484 24 - 312862 25 - 312730 26 - 314328 27 - 313142 28 - 313510 29 - 313830 30 - 313378 31 - 313414 32 - 314185 33 - 313059 34 - 313019 35 - 313368 36 - 312500 37 - 312859 38 - 313713 39 - 313394 40 - 313719 41 - 312837 42 - 312799 43 - 313907 44 - 312424 45 - 313071 46 - 313576 47 - 312796 48 - 313857 49 - 314417 50 - 313918 51 - 313099 52 - 313396 53 - 312824 54 - 313566 55 - 312437 56 - 313856 57 - 313413 58 - 313091 .....